多核编程中的mutex问题
#define THREAD_NUMBER 2
static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
[color=#FF00FF]//线程1对mutex加锁[/color]
void*thread1(void*arg)
{
pthread_mutex_lock(&mutex);
printf("thread1 locked the mutex\n");
printf("thread1 is waiting for conditiond signal.....\n");
pthread_cond_wait(&cond,&mutex);
printf("thread1 received condition signal!\n");
pthread_mutex_unlock(&mutex);
printf("thread1 unlock the mutex!\n");
pthread_exit(NULL);
}
void *thread2(void*arg){
int i=0;
struct timeval old,new;
gettimeofday(&old);
new=old;
pthread_mutex_lock(&mutex);
printf("thread2 lock the mutex\n");
while(new.tv_sec-old.tv_sec<5){
sleep(1);
gettimeofday(&new);
i++;
printf("thread2 sleep %d seconds\n",i);
}
printf("thread1 calls pthread_cond_sigal.....\n");
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
printf("thread2 unlocked the mutex\n");
pthread_exit(NULL);
}
int main(int argc,char *argv[]){
int i;
int ret_val;
pthread_t pt[THREAD_NUMBER];
ret_val=pthread_create(&pt[0],NULL,thread1,NULL);
if(ret_val!=0){
printf("pthread_create error!\n");
exit(1);
}
ret_val=pthread_create(&pt[1],NULL,thread2,NULL);
if(ret_val!=0){
printf("pthread_create error!\n");
exit(1);
}
for(i=0;i<THREAD_NUMBER;i++){
ret_val=pthread_join(pt[i],NULL);
if(ret_val!=0){
printf("pthread_join error!\n");
exit(1);
}
}
return 0;
}
输出的结果是:
thread1 locked the mutex
thread1 is waiting for conditiond signal.....
thread2 lock the mutex //为什么在thread1还没有对mutex解锁的时候,thread2能对mutex加锁呢????
thread2 sleep 1 seconds
thread2 sleep 2 seconds
thread2 sleep 3 seconds
thread2 sleep 4 seconds
thread2 sleep 5 seconds
thread1 received condition signal!
thread2 unlocked the mutex
thread1 received condition signal!
thread1 unlock the mutex!
还有就是pthread_join函数到底有什么用处,我看了书,不是很理解!!
请各位帮忙解答!!谢谢