在C中创建线程

时间:2013-03-23 23:53:20

标签: 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: 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);

}

3 个答案:

答案 0 :(得分:8)

您应该编译并链接-pthread

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

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

答案 1 :(得分:5)

您尚未链接pthread库。编译:

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

答案 2 :(得分:2)

更改

void func(void)

void* func(void *)

并使用

进行编译
gcc hilo.c -pthread

您只会在打印pthread_self()时遇到错误,因为它不是int