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