1
我是相当新的线程编程,我想测试互斥锁功能。所以我编写了以下内容来测试它。Pthreads:主要覆盖互斥锁
** 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()'所有的线程...... – twalberg 2014-09-04 14:06:36
'main()'在第一个线程在'sleep(6)'中并且破坏互斥锁之前已经改变了标志变量。输出看起来像这样: '** THREAD 0 **开始。当前标志是1.' '线程0在main中初始化并且标志值为:1' '线程1在main中初始化并且标志值为: 1' '线程2在main中初始化,标志值为:2' '线程3在main中初始化并且标志值为:3' '线程4在main中初始化并且标志值为:4' ' * THREAD 1 **开始,当前标志为5.' '** THREAD 2 **开始。当前标志为6.' ... 等。 – iandi 2014-09-04 14:33:15