不知道是不是被linux的系统信号影响,还是这些函数本身机制不能实现这样的同步.

代码:
#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;
}
结果:
上面是用信号量系列函数来控制线程同步,如果换成互斥系列函数,结果也是一样,不能同步.




慕森王
浏览 40回答 1
1回答

慕丝7291255

你的问题不是互斥的问题,而是传给子线程的 i 是指针,在子线程获取 *arg 时,主线程的 for 循环可能已经修改或者没有修改 i 的值,从而出现问题。下面的代码直接把 i 的值传给子线程,而不是传指针,就不会有问题了。#include&nbsp;<iostream>using&nbsp;namespace&nbsp;std;#include&nbsp;<pthread.h>#include&nbsp;<semaphore.h>sem_t&nbsp;g_sem;pthread_mutex_t&nbsp;g_mutex;static&nbsp;int&nbsp;g_count&nbsp;=&nbsp;0;const&nbsp;int&nbsp;THREAD_NUM&nbsp;=&nbsp;100;void*&nbsp;ProcThread(void*&nbsp;arg){&nbsp;&nbsp;&nbsp;&nbsp;long&nbsp;iNum&nbsp;=&nbsp;(long)&nbsp;arg;sem_post(&g_sem);pthread_mutex_lock(&g_mutex);sleep(2);g_count&nbsp;=&nbsp;g_count&nbsp;+&nbsp;1;cout&nbsp;<<&nbsp;"child&nbsp;thread&nbsp;num&nbsp;=&nbsp;"&nbsp;<<&nbsp;iNum&nbsp;<<&nbsp;",&nbsp;count&nbsp;=&nbsp;"&nbsp;<<&nbsp;g_count&nbsp;<<&nbsp;endl;pthread_mutex_unlock(&g_mutex);pthread_exit(NULL);return&nbsp;NULL;}int&nbsp;main()&nbsp;{sem_init(&g_sem,&nbsp;0,&nbsp;1);pthread_mutex_init(&g_mutex,&nbsp;NULL);pthread_t&nbsp;childThread[THREAD_NUM];for&nbsp;(int&nbsp;i=0;&nbsp;i<THREAD_NUM;&nbsp;++i){sem_wait(&g_sem);int&nbsp;iRet&nbsp;=&nbsp;pthread_create(childThread&nbsp;+&nbsp;i,&nbsp;NULL,&nbsp;ProcThread,&nbsp;(void&nbsp;*)i);if&nbsp;(iRet&nbsp;!=&nbsp;0){cout&nbsp;<<&nbsp;"error&nbsp;=&nbsp;"&nbsp;<<&nbsp;iRet&nbsp;<<&nbsp;endl;}}for&nbsp;(int&nbsp;i=0;&nbsp;i<THREAD_NUM;&nbsp;++i){pthread_join(childThread[i],&nbsp;NULL);}sem_destroy(&g_sem);pthread_mutex_destroy(&g_mutex);cout&nbsp;<<&nbsp;"!!!Hello&nbsp;World!!!"&nbsp;<<&nbsp;endl;&nbsp;//&nbsp;prints&nbsp;!!!Hello&nbsp;World!!!return&nbsp;0;}
打开App,查看更多内容
随时随地看视频慕课网APP