在C语言中创建线程

3
我正在尝试使用gcc -Wall -std=c99 hilo.c命令运行这个C程序,但是在执行./a.out hilo.c时出现了以下错误信息:
hilo.c: In function ‘func’:
hilo.c:6:3: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘pthread_t’ [-Wformat]
hilo.c: In function ‘main’:
hilo.c:14:3: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [enabled by default]
/usr/include/pthread.h:225:12: note: expected ‘void * (*)(void *)’ but argument is of type ‘void (*)(void)’
hilo.c:15:3: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [enabled by default]
/usr/include/pthread.h:225:12: note: expected ‘void * (*)(void *)’ but argument is of type ‘void (*)(void)’
hilo.c:24:3: warning: statement with no effect [-Wunused-value]
/tmp/cchmI5wr.o: In function `main':
hilo.c:(.text+0x52): undefined reference to `pthread_create'
hilo.c:(.text+0x77): undefined reference to `pthread_create'
hilo.c:(.text+0x97): undefined reference to `pthread_join'
hilo.c:(.text+0xab): undefined reference to `pthread_join'
collect2: ld returned 1 exit status

我不知道代码出了什么问题,如果有人能帮忙解决,将不胜感激。

以下是代码:

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

void func(void){

         printf("thread %d\n", pthread_self());
         pthread_exit(0);

}

   int main(void){

        pthread_t hilo1, hilo2;

        pthread_create(&hilo1,NULL, func, NULL);
        pthread_create(&hilo2,NULL, func, NULL);

        printf("the main thread continues with its execution\n");

        pthread_join(hilo1,NULL);
        pthread_join(hilo2, NULL);

        printf("the main thread finished");

        scanf;

  return(0);

}

1
@MichaelBurr:很不幸,但如果其他问题有一个错误的答案被接受,我不想将其标记为重复。 - Dietrich Epp
@Dietrich:很遗憾的是,SO上没有某种社区/管理员/其他人对采纳答案进行覆盖的机制(我想可以说票数应该起到这个作用)。我们还不知道正确的答案是否会被接受。 - Michael Burr
3个回答

8

你应该使用-pthread进行编译和链接。

gcc -Wall -std=c99 hilo.c -pthread

仅使用-lpthread是不够的。 -pthread标志将更改一些libc函数的工作方式,以使它们在多线程环境下正确工作。


1
你的答案取决于平台。在某些情况下,即使我怀疑在这种情况下你是正确的,-pthread也是必需的。并不是每个支持pthreads的系统都是这样的。 - Randy Howard

5

您还没有链接pthread库。请使用以下命令进行编译:

gcc -Wall -std=c99 hilo.c -lpthread

我还应该补充一点,这是 POSIX 的一种通用方式来链接 任何 库(-l)。而在 pthreads 的情况下,它取决于编译器和 libc,即当使用 -pthread 时,gcc 设置了其他选项/开关,这些选项/开关可能不会与 -lpthread 一起设置(甚至可能导致 libc 的功能不正确)。这是非常 gcc 特定的。更一般的答案是:尽可能使用 -pthread。如果没有,请使用 -lpthread,并通过阅读其文档设置任何其他必要的选项/编译器开关以确保您的平台/编译器的正确运行。 - P.P

2

更改

void func(void)

to

void* func(void *)

并且编译

gcc hilo.c -pthread

如果对 pthread_self() 使用了 int 类型,就会在打印时出现错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接