代码:#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 关注
 - 87 浏览
 
添加回答
举报
0/150
	提交
		取消
	