【发布时间】:2014-09-04 23:18:03
【问题描述】:
我是线程编程的新手,我想测试互斥锁功能。所以我编写了以下代码来测试它。
**thread_test.h
...
extern int flags;
extern pthread_mutex my_mutex;
...
**thread_test.c
...
#include"thread_test.h"
...
void * thread_test(void *thread_parameters)
{
long tid = (long) thread_parameters;
pthread_mutex_lock(&my_mutex);
++flags;
printf("**THREAD %d** started. Flag value is %d.\n",tid, flags);
sleep(6);
pthread_mutex_unlock(&my_mutex);
pthread_exit(NULL);
}
...
**main.c
...
#include"thread_test.h"
...
#define THREADS 5
pthread_t threads[THREADS];
pthread_mutex_t my_mutex;
int flags = 0;
...
int main(){
int rct;
for(rct = 0; rct<THREADS; rct++)
if(pthread_create(&threads[rct],NULL, thread_test, (void *)rct))
printf("ERROR!")
else
{
sleep(1);
printf("Thread %d initialised in main and the flags value is %d.\n", rct,flags);
}
pthread_mutex_destroy(&my_mutex);
...
看来,即使我在子线程中锁定了互斥锁,主程序还是会在线程拥有互斥锁时以某种方式覆盖互斥锁,并为变量标志分配一个新值..
有人知道为什么会这样吗?
【问题讨论】:
-
很可能,
main()在任何线程有机会运行之前就到达了pthread_mutex_destroy()(我不确定pthread_mutex_destroy()是否真的关心互斥锁是否被锁定或不...)。在销毁互斥锁之前,您可能应该pthread_join()所有线程... -
main()已经更改了标志变量,因为第一个线程在sleep(6)中并且在它破坏互斥锁之前。输出如下所示:**THREAD 0** started.The current flag is 1.Thread 0 initialized in main and the flag value is : 1Thread 1 initialized in main and the flag value is : 1Thread 2 initialized in main and the flag value is : 2Thread 3 initialized in main and the flag value is : 3Thread 4 initialized in main and the flag value is : 4**THREAD 1** started.The current flag is 5.**THREAD 2** started.The current flag is 6....等..
标签: c multithreading pthreads