C 代码 -- Pthread 未编译

C Code -- Pthread Not Compiling

我在编译我的代码时遇到问题,它使用了互斥量(因此使用了 pthread 锁和条件)。我已经尝试包含头文件,使用 -pthread 或 -lpthread 进行编译,但我仍然遇到错误。将不胜感激。

这是错误输出:

函数‘Pthread_mutex_lock’的隐式声明[-Wimplicit-function-declaration] Pthread_mutex_lock(&锁); //锁定 ^ /tmp/cchVS47i.o: 在函数中 getMessage1': hw3.c:(.text+0x22): undefined reference toPthread_mutex_lock' hw3.c:(.text+0x50): 对 Pthread_mutex_lock' /tmp/cchVS47i.o: In functiongetMessage2' 的未定义引用: hw3.c:(.text+0x13e): 对“Pthread_mutex_lock”的未定义引用 collect2:错误:ld 返回了 1 个退出状态

这里是我的代码的相关部分(为清楚起见进行了编辑):

#define _GNU_SOURCE
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>

char message[1001];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;

void *getMessage1()
{
Pthread_mutex_lock(&lock); //locked

 ....
}

int main(void)
{
pthread_t id1;
pthread_t id2;

pthread_create((&id1), NULL, getMessage1, NULL);
pthread_create((&id2), NULL, getMessage2, NULL);

...

return 0;
}

就是你在

中的大写P

Pthread_mutex_lock(&lock); //locked

在函数 getmessage1() 的开头。

您的编译器抱怨它在编译阶段没有看到该函数的声明。它还在链接阶段抱怨这一点。您包含了所有正确的库,因为它不会抱怨任何其他正确键入的函数。

函数的正确名称是pthread_mutex_lock()。

在原始的 k&r C 中,可以使用不带声明的函数,尽管编译器会警告它们。在更现代的 C (99) 版本中,这已被弃用。