gpt4 book ai didi

编译线程程序

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:57 25 4
gpt4 key购买 nike

我用 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 中找到它需要的任何东西并忽略它。

关于编译线程程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20449569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com