使用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 %dn",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 semaphoren");
    exit(1);
  }
  s = pthread_create(&t1, NULL, threadFunc, &loops);
  if (s != 0) {
    printf("Error, creating threadsn");
    exit(1);
  }
  s = pthread_create(&t2, NULL, threadFunc, &loops);
  if (s != 0) {
    printf("Error, creating threadsn");
    exit(1);
  }
  s = pthread_create(&t3, NULL, threadFunc, &loops);
  if (s != 0) {
    printf("Error, creating threadsn");
    exit(1);
  }
  s = pthread_create(&t4, NULL, threadFunc, &loops);
  if (s != 0) {
    printf("Error, creating threadsn");
    exit(1);
  }
  s = pthread_join(t1, NULL);
  if (s != 0) {
    printf("Error, creating threadsn");
    exit(1);
  }
  s = pthread_join(t2, NULL);
  if (s != 0) {
    printf("Error, creating threadsn");
    exit(1);
  }
  s = pthread_join(t3, NULL);
  if (s != 0) {
    printf("Error, creating threadsn");
    exit(1);
  }
  s = pthread_join(t4, NULL);
  if (s != 0) {
    printf("Error, creating threadsn");
    exit(1);
  }
  printf("glob value %d n", glob);
  exit(0);
}

当我尝试使用threadFunc中的print语句打印glob时,glob的期望值是什么?他们是20岁、40岁、60岁和80岁吗?当我执行上面的程序时,我会得到类似glob的不同值,61、50、73和80!!还是29,76,78,80?为什么?每次执行时,我都会得到不同的glob值。我认为这与信号量有关,但glob的值怎么会像我给你的第一个输出示例中那样减少呢?

此外,赋予pthread_create的thread_initiate的目的是什么?不是专门针对threadFunc,但一般来说,使用传递给pthread_create的thread_initiate函数处理c中线程的程序员通常会做什么?

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

至于第二部分,我相信启动例程就是线程要运行的代码。

感谢@WhozCraig和@JoachimPileborg的帮助!

最新更新