使用 pthread.c 创建线程

标签 c multithreading pthreads semaphore

我正在尝试学习如何使用 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/

相关文章:

java - JAVA 中的守护进程线程组是什么?

c - C中的线程,如何使用它们来移动玩家?

c++ - 如何获取正确的线程 ID 和值

c - fopen 无法读取文件(文件始终等于 NULL)

c++ - 运行时C++数组初始化问题

php - 如何从 c/c++ php 扩展中包含/需要一个 php 文件,将变量传递给用户空间范围?

c++ - 在多线程进程中处理信号的例子

android - 使用 Handler 从线程更新 UI 时出错

c - glibc 中 pthread 堆栈的分配

c - 如何衡量ARM性能?