在C中创建线程

在C中创建线程,c,pthreads,undefined-reference,C,Pthreads,Undefined Reference,我正在尝试使用gcc-Wall-std=c99 hilo.C-./a.out hilo.C运行此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: warnin

我正在尝试使用gcc-Wall-std=c99 hilo.C-./a.out hilo.C运行此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);

}
#包括
#包括
无效函数(无效){
printf(“线程%d\n”,pthread_self());
pthread_退出(0);
}
内部主(空){
pthread_t hilo1,hilo2;
pthread_create(&hilo1,NULL,func,NULL);
pthread_create(&hilo2,NULL,func,NULL);
printf(“主线程继续执行\n”);
pthread_join(hilo1,NULL);
pthread_join(hilo2,NULL);
printf(“完成的主螺纹”);
scanf;
返回(0);
}

您尚未链接pthread库。编译时使用:

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

您应该编译并链接
-pthread

gcc -Wall -std=c99 hilo.c -pthread
仅使用
-lpthread
是不够的。
-pthread
标志将更改某些libc函数的工作方式,以使它们在多线程环境中正确工作。

更改

void func(void)

并用

gcc hilo.c -pthread

您只能在打印
pthread_self()
时出错,因为它不是
int

@MichaelBurr:很不幸,但是,如果另一个问题的答案被接受了,我不想把它标记为重复。@Dietrich:很遗憾,没有某种社区/版主/任何可以替代被接受答案的东西(我想有人可能会认为投票数应该是这样的)。我们还没有看到正确的答案是否被接受。你的答案取决于平台。在某些情况下,-pthread是必要的,尽管我怀疑在本例中您是正确的。这并不是说在每个支持pthreads的系统上都是这样的,我还应该补充一点,这是一种POSIX方式来链接任何库(-l)。而对于pthreads,则是编译器和libc相关的情况,即当使用
-pthread
时,gcc设置了额外的选项/开关,这些选项/开关可能不会与
-lpthread
一起设置(甚至可能导致libc的功能不正确)。这是非常具体的。更一般的答案是:只要可用,就使用
-pthread
。如果没有,请使用
-lpthread
,并确保通过阅读平台/编译器的文档来设置平台/编译器正确运行所需的任何其他选项/编译器开关。
gcc hilo.c -pthread