代碼:#include <iostream>using namespace std;#include <pthread.h>#include <semaphore.h>sem_t g_sem;pthread_mutex_t g_mutex;static int g_count = 0;const int THREAD_NUM = 100;void* ProcThread(void* arg){int iNum = *(int*)arg;sem_post(&g_sem);pthread_mutex_lock(&g_mutex);sleep(2);g_count = g_count + 1;cout << "child thread num = " << iNum << ", count = " << g_count << endl;pthread_mutex_unlock(&g_mutex);pthread_exit(NULL);return NULL;}int main() {sem_init(&g_sem, 0, 1);pthread_mutex_init(&g_mutex, NULL);pthread_t childThread[THREAD_NUM];for (int i=0; i<THREAD_NUM; ++i){sem_wait(&g_sem);int iRet = pthread_create(childThread + i, NULL, ProcThread, &i);if (iRet != 0){cout << "error = " << iRet << endl;}}for (int i=0; i<THREAD_NUM; ++i){pthread_join(childThread[i], NULL);}sem_destroy(&g_sem);pthread_mutex_destroy(&g_mutex);cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!return 0;}結果:上面是用信號量系列函數來控制線程同步,如果換成互斥系列函數,結果也是一樣,不能同步.
1 回答

慕絲7291255
TA貢獻1859條經驗 獲得超6個贊
你的問題不是互斥的問題,而是傳給子線程的 i 是指針,在子線程獲取 *arg 時,主線程的 for 循環可能已經修改或者沒有修改 i 的值,從而出現問題。下面的代碼直接把 i 的值傳給子線程,而不是傳指針,就不會有問題了。
#include <iostream> using namespace std; #include <pthread.h> #include <semaphore.h> sem_t g_sem; pthread_mutex_t g_mutex; static int g_count = 0; const int THREAD_NUM = 100; void * ProcThread( void * arg) { long iNum = ( long ) arg; sem_post(&g_sem); pthread_mutex_lock(&g_mutex); sleep(2); g_count = g_count + 1; cout << "child thread num = " << iNum << ", count = " << g_count << endl; pthread_mutex_unlock(&g_mutex); pthread_exit(NULL); return NULL; } int main() { sem_init(&g_sem, 0, 1); pthread_mutex_init(&g_mutex, NULL); pthread_t childThread[THREAD_NUM]; for ( int i=0; i<THREAD_NUM; ++i) { sem_wait(&g_sem); int iRet = pthread_create(childThread + i, NULL, ProcThread, ( void *)i); if (iRet != 0) { cout << "error = " << iRet << endl; } } for ( int i=0; i<THREAD_NUM; ++i) { pthread_join(childThread[i], NULL); } sem_destroy(&g_sem); pthread_mutex_destroy(&g_mutex); cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! return 0; } |
- 1 回答
- 0 關注
- 72 瀏覽
添加回答
舉報
0/150
提交
取消