Ral*_*lph 349 c linux multithreading pthreads
我从网上从https://computing.llnl.gov/tutorials/pthreads/上摘下了以下演示
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
Run Code Online (Sandbox Code Playgroud)
但是当我在我的机器上编译它(运行Ubuntu Linux 9.04)时,我收到以下错误:
corey@ubuntu:~/demo$ gcc -o term term.c
term.c: In function ‘main’:
term.c:23: warning: incompatible implicit declaration of built-in function ‘exit’
/tmp/cc8BMzwx.o: In function `main':
term.c:(.text+0x82): undefined reference to `pthread_create'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
这对我没有任何意义,因为标题包含pthread.h,应具有该pthread_create功能.有什么想法会出错吗?
Emp*_*ian 644
到目前为止,这个问题的答案都不正确.
对于Linux,正确的命令是:
gcc -pthread -o term term.c
Run Code Online (Sandbox Code Playgroud)
通常,库应该遵循命令行中的源和对象,而-lpthread不是"选项",它是库规范.在仅libpthread.a安装的系统上,
gcc -lpthread ...
Run Code Online (Sandbox Code Playgroud)
将无法链接.
Ruf*_*fus 19
我相信,加入适当的方式pthread在CMake与以下
find_package (Threads REQUIRED)
target_link_libraries(helloworld
${CMAKE_THREAD_LIBS_INIT}
)
Run Code Online (Sandbox Code Playgroud)
dyl*_*nin 15
实际上,如果您继续阅读以下教程,它会给出几个用于pthreads代码的编译命令的例子,如下表所示:
https://computing.llnl.gov/tutorials/pthreads/#Compiling

Ale*_*ich 13
从Linux终端运行,对我有用的是使用以下命令进行编译(假设我要编译的c文件名为test.c):
gcc -o test test.c -pthread
Run Code Online (Sandbox Code Playgroud)
希望它能帮助别人!
Gop*_* BG 10
对于Linux,正确的命令是:
gcc -o term term.c -lpthread
Run Code Online (Sandbox Code Playgroud)
如果您使用的是cmake,则可以使用:
add_compile_options(-pthread)
Run Code Online (Sandbox Code Playgroud)
要么
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")
Run Code Online (Sandbox Code Playgroud)