亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

不知道是不是被linux的系統信號影響,還是這些函數本身機制不能實現這樣的同步.

不知道是不是被linux的系統信號影響,還是這些函數本身機制不能實現這樣的同步.

慕森王 2023-03-03 21:14:42
代碼:#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;}
查看完整回答
反對 回復 2023-03-06
  • 1 回答
  • 0 關注
  • 72 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號