使用 pthread.c 创建线程

creating threads using pthread.c

我正在尝试学习如何使用 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 函数做什么?

我想通了,我没有把代码想好。线程 运行ning 并发,因此无法确定 glob 的值。如果两个线程 运行ning,第一个可能是循环中的 5 个值,第二个线程可能是 2 个值,这意味着 glob 的值为 7。打印 glob 时,该值将始终大于20 的倍数(对于这个特定问题)。

至于第二部分,我认为起始例程是线程将要执行的代码 运行。

感谢@WhozCraig 和@JoachimPileborg 的帮助!