【问题标题】:How to run this threads example?如何运行这个线程示例?
【发布时间】:2012-07-16 00:28:57
【问题描述】:

我正在尝试 Tanenbaum 的 3e“现代操作系统”中的代码,但出现编译器错误和警告:

$ LANG=en_US.UTF-8 cc thread.c 
thread.c: In function ‘main’:
thread.c:19:63: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
thread.c:25:1: warning: passing argument 1 of ‘exit’ makes integer from pointer without a cast [enabled by default]
/usr/include/stdlib.h:544:13: note: expected ‘int’ but argument is of type ‘void *’
/tmp/ccqxmMgE.o: In function `main':
thread.c:(.text+0x57): undefined reference to `pthread_create'
collect2: ld returned 1 exit status

这是我正在尝试的代码

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define NUMBER_OF_THREADS   10

void *print_hello_world(void *tid)
{
  //printf("Hello World. Greetings from thread %d0", tid);
  pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
  pthread_t threads[NUMBER_OF_THREADS];
  int status, i;

  for(i=0; i<NUMBER_OF_THREADS; i++) {
  //printf("Main here creating thread %d0", i);
  status = pthread_create(&threads[i], NULL, print_hello_world, (void *)i);

  if (status != 0) {
    //printf("Oops. pthread_create returned error code %d0", status);
    exit(-1);
  }
}
exit(NULL);
}

您能帮我改进代码的状态以使其能够运行吗?由于书中的确切代码无法编译,因此似乎存在一些勘误表。谢谢

【问题讨论】:

  • 这个“警告:传递 'exit' 的参数 1 会在没有强制转换的情况下从指针生成整数 [默认启用]”似乎是因为您使用的是 exit(NULL) 而不是 exit(-1)

标签: c operating-system pthreads


【解决方案1】:

请通过在链接器中指定 -lpthread 选项来链接到 pthread 库。

另外,您应该使用pthread_join 等待所有创建的线程完成。

【讨论】:

  • pthread_exit(NULL) 也是一个可能的解决方案。你可以在 exit(NULL) 之前添加。
  • 这很有趣,也解决了printf 调用。 printf 也是从 pthread 库中定义的吗?
【解决方案2】:
$gcc thread.c -lpthread


这是链接pthread共享库的。

【讨论】:

  • 太棒了!当我现在从 a.out 得到这个输出时,它似乎工作了:Main here creating thread 00Main here creating thread 10Hello World. Greetings from thread 00Main here creating thread 20Hello World. Greetings from thread 10Main here creating thread 30Main here creating thread 40Main here creating thread 50Main here creating thread 60Hello World. Greetings from thread 50Hello World. Greetings from thread 40Hello World. Greetings from thread 30Hello World. Greetings from thread 20Main here creating thread 70Hello World. Greetings from thread 60Main here creating thread 80Hello World...
【解决方案3】:

1) 您必须链接到 libpthread 才能摆脱链接器错误:

gcc ..... -lpthread

(注意 -lpthread 选项必须是最后一个)!

2) exit(NULL); 错误; NULL 用于指针类型,而 exit 希望提供一个 int ;简单地使用

exit(0);

改为。

其他警告只是系统相关的指针和整数大小警告;在大多数情况下可以放心地忽略它们。

【讨论】:

    【解决方案4】:

    Pl。在这种情况下,不要在 main 函数中使用 exit 语句,因为 main 可能会退出,并且您的线程也将终止,并且您可能无法在线程函数中获得 print 语句的输出。

    Pl。在 main 中使用 pthread_exit 而不是 exit,这样即使您的主线程终止,其他线程也可以继续。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多