C语言 在 C 中创建线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15593455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
creating threads in C
提问by user2188946
I am trying to run this C program using gcc -Wall -std=c99 hilo.c - ./a.out hilo.c and I am getting this error message:
我正在尝试使用 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
No idea what's wrong with the code so if anyone could help me would be it would be appreciated.
不知道代码有什么问题,所以如果有人能帮助我,我将不胜感激。
This is the code:
这是代码:
#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);
}
回答by Dietrich Epp
You should compile and link with -pthread.
您应该编译并链接-pthread.
gcc -Wall -std=c99 hilo.c -pthread
It is not sufficient to use -lpthread. The -pthreadflag will change how some libc functions work, in order to make them work correctly in a multithreaded environment.
使用-lpthread. 该-pthread标志将更改某些 libc 函数的工作方式,以使它们在多线程环境中正常工作。
回答by P.P
You haven't linked the pthread library. Compile with:
您尚未链接 pthread 库。编译:
gcc -Wall -std=c99 hilo.c -lpthread
回答by Ralf Rafael Frix
Change
改变
void func(void)
to
到
void* func(void *)
and compile with
并编译
gcc hilo.c -pthread
You will only have errors in printing pthread_self()because it is not an int.
您只会在打印时出错,pthread_self()因为它不是int.

