并发编程实验一

Posted masterchd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了并发编程实验一相关的知识,希望对你有一定的参考价值。

#include <bits/stdc++.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#include <error.h>
#include <sys/times.h>
using namespace std;
#define Producer 2
#define Customer 2
#define BufferSize 5
#define Threadnum 5
int Buffer[BufferSize];
pthread_t threads[Customer+Producer];
//the model of Customer
sem_t canuseBuffers;//the messagebuffer free
sem_t canuseProduct;
pthread_mutex_t Mutex;
int Point_in=0;
int Point_out=0;
int Customer_id = 0;
int Producer_id = 0;
void * Custome(void *args)
{
    long num = (long)args;
    while(1)
    {
        sem_wait(&canuseProduct);//-- it
        pthread_mutex_lock(&Mutex);
        printf("pthread %d began to read!\n",num);
        Customer_id=Buffer[Point_out];//get a product
        Point_out = (Point_out+1)%BufferSize;
        sem_post(&canuseBuffers);//++ it
        pthread_mutex_unlock(&Mutex);
        printf("thread read over\n");
        sleep(1);
    }
    return NULL;
}
void * Produce(void *args)
{
    long num = (long)args;
    while(1)
    {
        sem_wait(&canuseBuffers);//--it
        pthread_mutex_lock(&Mutex);
        printf("pthread  %d began to write\n",num);
        sem_post(&canuseProduct);//++it
        pthread_mutex_unlock(&Mutex);
        sleep(5);
    }
    return NULL;
}
int main()
{
    sem_init(&canuseBuffers,0,BufferSize);
    sem_init(&canuseProduct,0,0);
    pthread_mutex_init(&Mutex,NULL);
    for(int i=0;i<Customer;i++)
    {
        int rc = 0;
        rc = pthread_create(&threads[i],NULL,Custome,(void *)i);
        if(rc)
        {
            printf("Error\n");
        }
        printf("thread %d are request read\n",i);
    }
    for(int i=0;i<Customer+Producer;i++)
    {
        int rc = 0;
        rc = pthread_create(&threads[i],NULL,Produce,(void *)i);
        if(rc)
        {
            printf("Error!\n");
        }
        printf("thread %d are request write\n",i);
    }
    for(int i=0;i<Customer+Producer;i++)
    {
        pthread_join(threads[i],NULL);
    }
}

 

以上是关于并发编程实验一的主要内容,如果未能解决你的问题,请参考以下文章

GORust这些新一代高并发编程语言为何都极其讨厌共享内存?

译丨Yarn - Javascript 新一代套件管理

使用 React 实验性中继片段:缺少属性 '"$fragmentRefs"'

全栈编程系列SpringBoot整合Shiro(含KickoutSessionControlFilter并发在线人数控制以及不生效问题配置启动异常No SecurityManager...)(代码片段

Java编程思想之二十 并发

网络编程之并发