操作系统 进行同步算法设计与实现
首先是 对 线程同步的实现
#include<bits/stdc++.h>
#include<windows.h>
using namespace std;
//信号量句柄
HANDLE sem;
DWORD WINAPI ChildThread(LPVOID){
// cout<< "子线程执行中";
cout<< "childthread running" << endl;
Sleep(1000);
ReleaseSemaphore(sem, 1, NULL);
// cout<< "子线程执行完毕";
cout<<"childthread over" << endl;
return 0;
}
int main(){
sem = CreateSemaphore(NULL, 0, 1, NULL);
// cout<< "父线程创建子线程";
cout<< "fatherchild build childthread" << endl;
HANDLE thread = CreateThread(NULL, 0, ChildThread, NULL, 0, NULL);
WaitForSingleObject (sem, 0x3f);
// cout<< "父线程收到信号, 继续执行";
cout<< "fatherthread recept, running" << endl;
return 0;
}
接着是对 进程互斥 的 实现
#include<bits/stdc++.h>
#include<windows.h>
using namespace std;
int counter = 0;
//信号量句柄
HANDLE mutex;
DWORD WINAPI Thread(LPVOID para){
int thread_id = *(int *)para;
WaitForSingleObject(mutex, 0x3f);
cout<< "Thread" << thread_id << "get mutex" <<endl;
counter += 10;
cout<< "current count: " << counter << endl;
ReleaseMutex(mutex);
return 0;
}
int main(){
mutex = CreateMutex(NULL, false, NULL);
HANDLE thread[2];
int id[2] = {1, 2};
for(int i = 0; i < 2; i ++){
thread[i] = CreateThread(NULL ,0 ,Thread, &id[i], 0, NULL);
}
WaitForMultipleObjects(2, thread, true, 0x3f);
cout << "final count: " << counter << endl;
return 0;
}
最后是经典的 线程同步问题 生产者消费者问题 的 初步模拟
#include<bits/stdc++.h>
#include<windows.h>
using namespace std;
//#define endl '\n'
const int buffer_size = 5;
int buffer[buffer_size];
int in = 0, out = 0;
HANDLE mutex;
HANDLE emptysem;
HANDLE fullsem;
DWORD WINAPI Producer(LPVOID){
while(1){
int item = rand() % 100;
WaitForSingleObject(emptysem, 0x3f);
WaitForSingleObject(mutex, 0x3f);
buffer[in] = item;
// cout<< "生产者放入[" << in << "]" << item << endl;
cout<< "producer put[" << in << "]" << item << endl;
in = (in + 1) % buffer_size;
ReleaseMutex(mutex);
ReleaseSemaphore(fullsem, 1 ,NULL);
Sleep(200);
}
return 0;
}
DWORD WINAPI Consumer(LPVOID){
while(1){
WaitForSingleObject(fullsem, 0x3f);
WaitForSingleObject(mutex, 0x3f);
int item = buffer[out];
// cout<< "消费者取出[" << out << "]" << item <<endl;
cout<< "consumer take[" << out << "]" << item <<endl;
out = (out + 1) % buffer_size;
ReleaseMutex(mutex);
ReleaseSemaphore(emptysem, 1 , NULL);
Sleep(500);
}
return 0;
}
int main(){
srand(time(NULL));
mutex = CreateMutex(NULL, false, NULL);
emptysem = CreateSemaphore(NULL, buffer_size, buffer_size, NULL);
fullsem = CreateSemaphore(NULL, 0, buffer_size, NULL);
HANDLE producer = CreateThread(NULL, 0, Producer, NULL, 0, NULL);
HANDLE consumer = CreateThread(NULL, 0, Consumer, NULL, 0, NULL);
Sleep(10000);
return 0;
}