以下代码是一个简单的线程游戏,它在线程间切换,导致计时器减少。pthread_exit和/或pthread_join导致Abort和SegFaults
它适用于3个线程,原因和中止(核心转储)为4个线程,并导致5个或更多线程seg故障。
任何人都知道为什么会发生这种情况?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <assert.h>
int volatile num_of_threads;
int volatile time_per_round;
int volatile time_left;
int volatile turn_id;
int volatile thread_running;
int volatile can_check;
void * player (void * id_in){
int id= (int)id_in;
while(1){
if(can_check){
if (time_left<=0){
break;
}
can_check=0;
if(thread_running){
if(turn_id==id-1){
turn_id=random()%num_of_threads;
time_left--;
}
}
can_check=1;
}
}
pthread_exit(NULL);
}
int main(int argc, char *args[]){
int i;
int buffer;
pthread_t * threads =(pthread_t *)malloc(num_of_threads*sizeof(pthread_t));
thread_running=0;
num_of_threads=atoi(args[1]);
can_check=0;
time_per_round = atoi(args[2]);
time_left=time_per_round;
srandom(time(NULL));
//Create Threads
for (i=0;i<num_of_threads;i++){
do{
buffer=pthread_create(&threads[i],NULL,player,(void *)(i+1));
}while(buffer == EAGAIN);
}
can_check=1;
time_left=time_per_round;
turn_id=random()%num_of_threads;
thread_running=1;
for (i=0;i<num_of_threads;i++){
assert(!pthread_join(threads[i], NULL));
}
return 0;
}
是的,我读过这个。但是,这是针对特定的学校作业。 我仔细printf调试了这个问题,它只围绕着pthread_exit/join调用...所以我不认为它是一个内存问题。 – mjames 2010-03-12 03:57:40
Protip:printf在多线程环境中告诉你什么都没有。 – 2010-03-12 04:14:21
他非常清楚地说明你的问题在答案的第一段中是什么......再次阅读。 – SoapBox 2010-03-12 04:14:55