在操作系统上机实验的时候,需要使用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学习小白,欢迎各位大佬指正