Tuesday, May 5, 2009

Windows multi-threading examples

Free Web Counter

Free Counter


These examples are based on the stanford CS107 lecture 15 - lecture 20.

youtube playlist


Since C++ multi-threading library is operation system dependent, the codes listed here are tested on Visual C++ 2008 Express Edition.

Windows Multithreading Helloworld
Several Agents are selling some amount of tickets in parallel, their access to the global parameter numTicketsp are synchronized by a Mutex.
-------------------------------
The following code is tested on Visual C++ 2008 Express Edition.
Show Code   Hide Code
--------------------------------


Simple Semaphor Example
A simple network server :
writer() grab data from network connection, then write characters to buffer, at the mean-time reader() constantly read character from the same buffer.
Two semaphors "emptyBuffer" and "fullBuffer" are used here to make sure reader() and writer() won't step onto each other.

-------------------------------
The following code is tested on Visual C++ 2008 Express Edition.
Show Code   Hide Code
--------------------------------



A little bit advanced Semaphor Example

Classic Five philosophers problem:
There are 5 philosophers who sit around a table. There is a folk between each neighboring philosopher. Each philosopher must grab two folks to be able to eat. Once a philosopher finished eating, he will put the forks back and waiting for the next chance to eat. The objective is to write a multi-threading program to simulate the situation.

The trick is -- suppose each philosopher is holding a folk at his/her left hand, and waiting for the philosopher at his right hand side to give up a fork. The philosopher at the right hand will not gonna to give up his fork, because he/she is also waiting for a fork from the right side...A dead-lock condition is thus created, nobody will be able to eat and they will be waiting forever.

To resolve the dead-lock, we only allow at most 4 philosophers to grab forks at any given moment, the rest philosophers have to wait.

The pseudocode is as follows:

Semaphore forks[]={1,1,1,1,1};
Semaphore numAllowedToEat(4);
void philosophor(int id)
{
for(int i=0; i<3; i++){
think();
SW(umAllowedToEat);
SW(forks[id]);
SW(forks[(id+1)%5]);
eat();
SS(forks[id]);
SS(forks[(id+1)%5]);
SS(numAllowedToEat);
}
-------------------------------
The following code is tested on Visual C++ 2008 Express Edition.
Show Code   Hide Code
--------------------------------

No comments:

Post a Comment

Why I stopped publishing blog posts as information provider

Now the AI can generate content. Does that mean the web publishing industry reaches the end? ChatGPT said: ChatGPT Not at all. While AI can ...