我正在尝试学习如何使用p线程库在c中创建线程,我使用了以下代码:
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
static int glob = 0;
static sem_t sem;
static void *threadFunc(void *arg) {
int loops = *((int *) arg);
int loc, j;
for (j = 0; j < loops; j++) {
if (sem_wait(&sem) == -1)
exit(2);
loc = glob;
loc++;
glob = loc;
if (sem_post(&sem) == -1)
exit(2);
}
printf("\n%d %d\n",glob/20,glob);
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t t1, t2, t3, t4;
int s;
int loops = 20;
if (sem_init(&sem, 0, 1) == -1) {
printf("Error, init semaphore\n");
exit(1);
}
s = pthread_create(&t1, NULL, threadFunc, &loops);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_create(&t2, NULL, threadFunc, &loops);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_create(&t3, NULL, threadFunc, &loops);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_create(&t4, NULL, threadFunc, &loops);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_join(t1, NULL);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_join(t2, NULL);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_join(t3, NULL);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
s = pthread_join(t4, NULL);
if (s != 0) {
printf("Error, creating threads\n");
exit(1);
}
printf("glob value %d \n", glob);
exit(0);
}
当我试图使用threadFunc中的print语句打印它们时,glob的期望值是多少?他们分别是20,40,60和80?当我执行上面的程序,我得到不同的值,例如,61,50,73和80!还是29,76,78,80怎么会这样?EVerytime我执行,我得到不同的值为glob。我认为这与信号量有关,但是glob的值怎么会像我给您的第一个输出示例那样减少呢?
此外,thread_initiate给pthread_create的目的是什么?具体而言,不是threadFunc,但是一般来说,c++中处理线程的程序员通常使用传递给pthread_create的thread_initiate函数来处理什么?
发布于 2015-02-28 14:54:28
我想清楚了,我没有正确地考虑代码。线程同时运行,因此无法决定glob的值。如果两个线程正在运行,第一个线程可能是循环中的5个值,第二个线程可能是2个值,这意味着glob值为7。当glob被打印时,值总是大于20的倍数(对于这个特殊的问题)。
至于第二部分,我认为启动例程是线程将要运行的代码。
感谢@WhozCraig和JoachimPileborg的帮助!
https://stackoverflow.com/questions/28785378
复制