Linux创建进程之对pthread_create未定义的引用

在操作系统上机实验的时候,需要使用pthread.h库创建、删除,定义线程。
在centos8中执行下列代码的时候出现了一个奇怪的错误
在这里插入图片描述

经过大佬指导发现,在linux中没有默认的pthread库,若需要使用#include<pthread.h>,需要在连接的时候使用libpthread.a这个库,当然,不能够在代码里面加上#include<libpthread.a>(不然又会很多奇奇怪怪的错误的)。对于这个我们只需要在终端生成可执行文件的时候加上一个参数即可:

$ vim PC_pthread.cpp
$ g++ PC_pthread.cpp -lpthread -o PC_pthread

只需再次输入

$ ./PC_pthread

就可以输出下列程序的结果

#include<bits/stdc++.h>
#include<unistd.h>
#include<pthread.h>//引入多线程
#include<sys/wait.h>
#include<sys/ipc.h>
#include<sys/time.h>
#include<sys/types.h>
//为了方便,我一般把超多头文件一起加进来(手动狗头)
using namespace std;
#define N 10
int full=0;//满缓冲区单元个数
int empty=N;//空缓冲区单元个数
int buffer=0;//缓冲区产品个数
pthread_mutex_t buffermutex=PTHREAD_MUTEX_INITIALIZER;//互斥信号量,控制对临界资源的访问
pthread_mutex_t buffermutexfull=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t buffermutexempty=PTHREAD_MUTEX_INITIALIZER;
void *Producer(void *)
{
    while(1)
    {
        while(empty==0);
        pthread_mutex_lock(&buffermutexempty);
        empty--;
        pthread_mutex_unlock(&buffermutexempty);
        pthread_mutex_lock(&buffermutex);
        buffer++;
        cout<<"Producer: buffer = "<<buffer<<"  full = "<<full<<"  empty = "<<empty<<"  empty+full = "<<empty+full<<endl;
        pthread_mutex_unlock(&buffermutex);
        sleep(rand() %2);
        pthread_mutex_lock(&buffermutexfull);
        full++;
        pthread_mutex_unlock(&buffermutexfull); 

    }
    pthread_exit(NULL);
}
void *Consumer(void *)
{
    while(1){
        while(empty==0);
        pthread_mutex_lock(&buffermutexfull);
        full--;
        pthread_mutex_unlock(&buffermutexfull);
        pthread_mutex_lock(&buffermutex);
        buffer--;
        cout<<"Consumer: buffer = "<<buffer<<"  full = "<<full<<"  empty = "<<empty<<"  empty+full = "<<empty+full<<endl;
        pthread_mutex_unlock(&buffermutex);
        sleep(rand() % 2);
        pthread_mutex_lock(&buffermutexempty);
        empty++;
        pthread_mutex_unlock(&buffermutexempty);
    }
    pthread_exit(NULL);
}
int main()
{
    pthread_t pro,con;//线程数组
    pthread_create(&pro,NULL,Producer,NULL);
    pthread_create(&con,NULL,Consumer,NULL);
    pthread_exit(NULL);
    return 0;
}

结果如下:
在这里插入图片描述

OS学习小白,欢迎各位大佬指正

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值