c语言线程同步的几种方式,c语言 多线程同步问题 跪求大神啊....

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

#include

#include

#include

#include "Semaphore.h"

#define NSTUDENTS 30

#define MAX_SERVINGS 100

// This shared variable gives the number of servings currently in the barrel

int servings;

//Initialization of semaphores and shared data

Semaphore beer_empty,beer_fill,mutex;

// Define here your semaphores and any other shared data

//Called by a student process. Do not modify this.

void drink_and_think() {

// Sleep time in milliseconds

int st = rand() % 1000;

Sleep(st);

}

// Called by a student process. Do not modify this.

void get_serving(int id)

{

if (servings > 0)

servings -= 1;

else

servings = 0;

printf("ID %d got a serving. %d left\n", id, servings);

}

// Called by the bartender process.

void refill_barrel()

{

servings = 1 + rand() % MAX_SERVINGS;

printf("Barrel refilled up to -> %d\n", servings);

}

//-- Implement a synchronized version of the student

void* student(void* ptr) {

int id = *(int*)ptr;

printf("Started student %d\n", id);

do{

wait(beer_fill);

if(servings==0){

signal(beer_empty);

//wait(beer_fill);

}else{

get_serving(id);

//drink_and_think();

signal(beer_fill);

drink_and_think();

}

}while(1);

}

//-- Implement a synchronized version of the bartender

void* bartender(void* ptr) {

int id = *(int*)ptr;

printf("Started bartender %d\n", id);

do{

wait(beer_empty);

Sleep(1000);

refill_barrel();

Sleep(1000);

signal(beer_fill);

}while(true);

}

int main() {

int n;

int sid[NSTUDENTS];

HANDLE sthr[NSTUDENTS], cthr;

//-- Initialize semaphores and shared data here

beer_empty = create(1);

beer_fill = create(0);

//mutex = create(1);

// Create the student and bartender threads. Do not modify.

for (n = 0; n < NSTUDENTS; ++n) sid[n] = n + 1;

for (n = 0; n < NSTUDENTS; ++n) {

sthr[n] = CreateThread(NULL, (DWORD)NULL,

(LPTHREAD_START_ROUTINE)student, (void*)(&sid[n]),

(DWORD)NULL, NULL);

}

int cid = 0;

cthr = CreateThread(NULL, (DWORD)NULL,

(LPTHREAD_START_ROUTINE)bartender, (void*)(&cid),

(DWORD)NULL, NULL);

Sleep(100000);

return 0;

}

这个为什么运行了一阵子以后会不动了。。。跪求大神

Semaphore.h 文件如下

#define Semaphore HANDLE

void wait(Semaphore h) { // wait for a semaphore

WaitForSingleObject( h, MAXLONG);

}

void signal(Semaphore h) { // signal a semaphore

ReleaseSemaphore(h,1,NULL);

}

Semaphore create(int v) { // create a semaphore with value v

return CreateSemaphore(NULL,(long)v, MAXLONG, NULL);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值