Posix线程与互斥锁

时间:2015-02-19 15:56:52

标签: multithreading

我已经开始研究POSIX线程了。我写了一个简单的代码。 我的问题是关于Mutex。 在线程函数内初始化互斥锁会产生错误的结果。在main函数内部(在创建线程之前)初始化互斥锁时,会得到正确的结果。为什么会这样?

计数值预计为200000,但它显示出一些不正确的值< 200000。

这是我的代码。

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <malloc.h>

void *thread_handler (void *name);
unsigned long int count=0;
pthread_mutex_t lock;

void main () {

pthread_t thread_num[2];
pthread_attr_t attr;
pthread_attr_init (&attr);

int i;
for (i=0;i<2;i++) {
if (pthread_create (&thread_num[i],&attr,(void *) thread_handler,NULL)<0) {

printf ("\n Error in Creating the Threads");

}

}
for (i=0;i<2;i++) {
pthread_join(thread_num[i],NULL); //Waiting for the Thread to Exit
}
printf ("\n The value of count=%ld\n",count);
}


void *thread_handler (void *arg) {
int i;
if (pthread_mutex_init (&lock,NULL)!=0) {
printf ("\n Error in Initializing the Mutex");
}


pthread_mutex_lock (&lock);


for (i=0;i<100000;i++) {
count++;
}

pthread_mutex_unlock(&lock);
pthread_exit(NULL);

}

先谢谢, NDPrasad。

1 个答案:

答案 0 :(得分:0)

初始化thread_handler函数内部的互斥锁时,它会初始化两次(因为您创建了两个执行此函数的线程)。它会导致未定义的行为(这意味着任何事情都可能发生)。

来自here的引用:

  

尝试初始化已初始化的互斥锁会导致未定义的行为。

相关问题