我正在尝试学习如何使用 pthread 库在 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吗?当我执行上面的程序时,我得到了不同的 glob 值,例如 61、50、73 和 80!或 29,76,78,80?怎么会?每次执行时,我都会得到不同的 glob 值。我认为这与信号量有关,但是 glob 的值如何像我给你的第一个输出示例中那样减少?
此外,给pthread_create的thread_initiate的目的是什么?不是具体的 threadFunc,而是一般来说,在 c 中处理线程的程序员通常使用传递给 pthread_create 的 thread_initiate 函数做什么?
最佳答案
我明白了,我没有正确考虑代码。线程是并发运行的,因此无法决定 glob 的值是什么。如果有两个线程正在运行,第一个线程可能是循环中的 5 个值,第二个线程可能是 2 个值,这意味着 glob 的值为 7。当打印 glob 时,该值将始终大于 20 的倍数(对于这个特定问题)。
至于第二部分,我认为启动例程是线程将要运行的代码。
感谢@WhozCraig 和@JoachimPileborg 的帮助!
关于使用 pthread.c 创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28785378/