當前位置:編程學習大全網 - 編程語言 - pv 原語實現生產者消費者問題,用C語言編程

pv 原語實現生產者消費者問題,用C語言編程

下面是我本學期做過的壹個課程設計

妳可以參考壹下,應該差不多

壹、如何建立線程

用到的頭文件

(a)pthread.h

(b)semaphore.h

(c) stdio.h

(d)string.h

定義線程標識

pthread_t

創建線程

pthread_create

對應了壹個函數作為線程的程序段

註意的問題

要保證進程不結束(在創建線程後加死循環)

在線程中加入While(1)語句,也就是死循環,保證進程不結束。

二、控制線程並發的函數

sem_t:信號量的類型

sem_init:初始化信號量

sem_wait:相當於P操作

sem_post:相當於V操作

三、實現原形系統

父親、母親、兒子和女兒的題目:

桌上有壹只盤子,每次只能放入壹只水果。爸爸專放蘋果,媽媽專放橘子,壹個兒子專等吃盤子中的橘子,壹個女兒專等吃盤子中的蘋果。分別用P,V操作和管程實現

每個對應壹個線程

pthread_t father; father進程

pthread_t mother; mother進程

pthread_t son; son進程

pthread_t daughter; daughter進程

盤子可以用壹個變量表示

sem_t empty;

各線程不是只做壹次,可以是無限或有限次循環

用While(1)控制各線程無限次循環

輸出每次是那個線程執行的信息

printf("%s\n",(char *)arg);通過參數arg輸出對應線程執行信息

編譯方法

gcc hex.c -lpthread

生成默認的可執行文件a.out

輸入./a.out命令運行

查看結果:程序連續運行顯示出

father input an apple.

daughter get an apple.

mother input an orange.

son get an orange.

mother input an orange.

son get an orange.

………………..

四、程序源代碼

#include <stdio.h>

#include<string.h>

#include <semaphore.h>

#include <pthread.h>

sem_t empty; //定義信號量

sem_t applefull;

sem_t orangefull;

void *procf(void *arg) //father線程

{

while(1){

sem_wait(&empty); //P操作

printf("%s\n",(char *)arg);

sem_post(&applefull); //V操作

sleep(7);

}

}

void *procm(void *arg) //mother線程

{

while(1){

sem_wait(&empty);

printf("%s\n",(char *)arg);

sem_post(&orangefull);

sleep(3);

}

}

void *procs(void *arg) //son線程

{

while(1){

sem_wait(&orangefull);

printf("%s\n",(char *)arg);

sem_post(&empty);

sleep(2);

}

}

void *procd(void *arg) //daughter線程

{

while(1){

sem_wait(&applefull);

printf("%s\n",(char *)arg);

sem_post(&empty);

sleep(5);

}

}

main()

{

pthread_t father; //定義線程

pthread_t mother;

pthread_t son;

pthread_t daughter;

sem_init(&empty, 0, 1); //信號量初始化

sem_init(&applefull, 0, 0);

sem_init(&orangefull, 0, 0);

pthread_create(&father,NULL,procf,"father input an apple."); //創建線程

pthread_create(&mother,NULL,procm,"mother input an orange.");

pthread_create(&daughter,NULL,procd,"daughter get an apple.");

pthread_create(&son,NULL,procs,"son get an orange.");

while(1){} //循環等待

}

  • 上一篇:面試題中有不懂的名詞可以要求考官解釋麽
  • 下一篇:李誌軍的經歷
  • copyright 2024編程學習大全網