Pthreads编译不起作用

时间:2012-02-06 22:11:43

标签: gcc pthreads

我已经编写了一些代码但是在编译它时似乎没有用。我试图在Ubuntu中运行它:

#include <pthread.h>
#include <ctype.h>
#include <unistd.h>

char buffer[128];

void *write_thread(void *args)
{
    int count = *((int*)args);
    write(STDOUT_FILENO, buffer, count);

    pthread_exit(0);
}

void *toupper_thread(void *args)
{
    int i;
    int count = *((int*)args);
    for(i = 0; i < count; i++) {
        buffer[i] = toupper(buffer[i]);
    }

    pthread_t writeId;
    pthread_create(&writeId, NULL, write_thread, &count);

    pthread_join(writeId, NULL);
    pthread_exit(0);
}

void *read_thread(void *args)
{
    int count = read(STDIN_FILENO, buffer, 128);
    pthread_t toupperId;
    pthread_create(&toupperId, NULL, toupper_thread, &count);

    pthread_join(toupperId, NULL);
    //buffer[count] = 0;

    pthread_exit(0);

}

int main()
{
    pthread_t threadId;
    pthread_create(&threadId, NULL, read_thread, NULL);

    pthread_join(threadId, NULL);
}

当我尝试使用gcc -pthread prob41.cgcc prob41.c -lpthread编译时出现这些错误:

   prob41.c:1:21: error: pthread.h: No such file or directory
   prob41.c: In function ‘toupper_thread’:
   prob41.c:23: error: ‘pthread_t’ undeclared (first use in this function)
   prob41.c:23: error: (Each undeclared identifier is reported only once
   prob41.c:23: error: for each function it appears in.)
   prob41.c:23: error: expected ‘;’ before ‘writeId’
   prob41.c:24: error: ‘writeId’ undeclared (first use in this function)
   prob41.c: In function ‘read_thread’:
   prob41.c:33: error: ‘pthread_t’ undeclared (first use in this function)
   prob41.c:33: error: expected ‘;’ before ‘toupperId’
   prob41.c:34: error: ‘toupperId’ undeclared (first use in this function)
   prob41.c: In function ‘main’:
   prob41.c:45: error: ‘pthread_t’ undeclared (first use in this function)
   prob41.c:45: error: expected ‘;’ before ‘threadId’
   prob41.c:46: error: ‘threadId’ undeclared (first use in this function)

我不知道我做错了什么。

3 个答案:

答案 0 :(得分:3)

您似乎错过了一些依赖项。

试试这个:

$ sudo apt-get install -y libc6-dev

答案 1 :(得分:1)

需要在编译命令中添加-I标志以使编译器能够找到pthread.h

答案 2 :(得分:1)

  • 系统中没有pthread.h库。尝试安装 适合它的图书馆。
  • 您需要确保使用#include <sys/type.h>
  • 编译时不要忘记添加-lpthread:gcc -lpthread {x}.c -o {y}