我用 C 编写了一个使用线程的简单程序。
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
//Global mutex variable
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//Shared variable
int x=100;
//Thread function
void *threadfunc(void *parm)
{
//Aquire lock
pthread_mutex_lock(&mutex);
printf ("Thread has aquire lock!\nIncrementing X by 100. . .\n");
x+=100;
printf ("x is %d \n", x);
pthread_mutex_unlock(&mutex);
return NULL;
}
//Main function
int main(int argc, char **argv)
{
pthread_t threadid;
//creating thread
pthread_create(&threadid, NULL, threadfunc, (void *) NULL );
//Aquire lock
pthread_mutex_lock(&mutex);
printf ("Main has aquire lock!\ndecrementing X by 100. . .\n");
x-=100;
printf ("x is %d \n", x);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
return 0;
}
当我编译它时,出现“未定义对 pthread create 的引用”的错误。我正在使用此命令进行编译:
gcc -lpthread thread.c -o thr
请您参考如下方法:
将 -lpthread
放在 thread.c
之后。 gcc 正在寻找库方法来满足它在查看库时已经看到的链接要求,因此当您将库放在第一位时,它不会从 pthread 中找到它需要的任何东西并忽略它。