Thread: learn multithreading

  1. #1
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715

    learn multithreading

    I want to learn multithreading programming.
    I know some basic thing about what processes and threads are,but didn't make any program. If someone can suggest some good tutorial with examples suitable for beginer with explanations.
    I read from msdn about CreateThread(...), CreateProcess(...) but I need to see some simple programs to gain real understanding. I found a lot of code on the internet, but there are a lot of complicated code, so I need a tutorial. Do you know some good links or has some recommendations?

  2. #2
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715

    multithreading example

    I need explanation of this simple program:
    Code:
    #include <windows.h>
    #include <iostream>
    using namespace std;
    void thread1();
    void thread2();
    int main()
    {
    	DWORD threadID1,threadID2;
    	HANDLE threads[2];
    	threads[0]=CreateThread(0,0,(LPTHREAD_START_ROUTINE)thread1,0,0,&threadID1);
    	threads[1]=CreateThread(0,0,(LPTHREAD_START_ROUTINE)thread2,0,0,&threadID2);
    	//WaitForMultipleObjects(2,threads,TRUE,INFINITE);
    }
    
    void thread1()
    {
    	cout<<"This is thread 1"<< " And this..."<<endl;
    }
    void thread2()
    {
    	cout<<"This is thread 2"<<endl;
    }
    First I'm not sure what is purpose of function WaitForMultipleObjects().
    If I remove comments I get the following output:
    Code:
    This is thread 1This is thread 2 And This...
    
    Press any key to continue
    As you can notice that one endl is simply ignored, and operator << is some kind of signal first is displayed text to << in thread1() and then second function thread2() is executed, and again thread1() is executed. What is really going on here I'm not sure. Maybe this output will be different on your machine.
    I have read in MSDN this:
    Code:
    The WaitForMultipleObjects function returns when one of the following occurs: 
    
    Either any one or all of the specified objects are in the signaled state. 
    The time-out interval elapses.
    How can I appy this explanation on my example?
    Thanks for help

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > As you can notice that one endl is simply ignored
    No, they're both at the end

    > first is displayed text to << in thread1() and then second function thread2() is executed
    One of the things you've got to get to grips with in thread programming is that anything can happen in any order. If they share a resource (say the screen) then all sorts of weird interactions are possible.
    A key idea in all of this is the idea of "atomic" operations - named so because they cannot be split into something smaller.

    So in your example, it looks like at every <<, the system takes the opportunity to see if any other thread can be run.

    > Maybe this output will be different on your machine.
    That seems likely

    > How can I appy this explanation on my example?
    Well do something like

    WaitForMultipleObjects(2,threads,TRUE,INFINITE);
    cout << "Back in main, threads finished" << endl;

    I presume the TRUE means "wait for all" and FALSE means "wait for any"
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715
    Thanks for replying Salem,
    yes I have noticed that things can happen in any order
    I put two for loops, one in every function, tried to display counters and saw what you tolod me.
    I have a lot of questions about this. I'll try to figure out on my own as much as I can, but it would be very helpfull if someone recommended me a good tutorial link so not to waste time experimenting and wondering why something is happening!
    Thanks

  5. #5
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    Posts
    4,829
    Unfortunately, my multithreading tutorial is not converted to my new web site yet.

    When a Windows programs main thread, your main() in this case, all threads it has spun are terminated. If you don't wait for the threads to finish, the main could exit before the threads do their work. It depends a lot on your machine of course, most modern machines will suceed with a simple job like that at least some of the time.

    To control access to global or shared resources, you need to use synchronisation routines. The easiest of these to understand is the Critical Section. Read this.
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

  6. #6
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715
    I need help with the following:
    I'm learning Synchronization and read about Dijkstra mutex:
    Code:
    indivisible access routines:
    V(s): [s = s + 1]
    P(s): [while(s == 0) {wait}; s = s - 1]
    The square braces surrounding the statements in the access routines indicate that the operations
    are indivisible, or atomic, operations.
    
    The P operation is intended to indivisibly test an integer variable and to block the calling
    process if the variable is not positive. The V operation indivisibly signals a blocked
    process to allow it to resume operation
    And have example with balance management:
    Code:
    suppose that two processes, p1 and p2, execute concurrently
    to access a common integer variable, balance. For example, thread p1 might handle credits
    to an account, while p2 handles the debits.
    Solution that uses mutex is:

    Code:
    proc_0() { 				proc_1() {
    ... ...
    /* Enter critical section */		 /* Enter critical section */
    P(mutex); 				P(mutex);
    balance = balance + amount;		 balance = balance - amount;
    /* Exit critical section */		/* Exit critical section */
    V(mutex);				 V(mutex);
    ... 					...
    }					}
    semaphore mutex = 1;
    fork(proc_0, 0);
    fork(proc_1, 0);
    I do understand conceptually this explanation, but problem is how to use that with functions such as CreateMutex() and ReleaseMutex().

    I'm having problems to understand how following example really works
    Code:
    a word processor program creates two threads, one to read a file and another to write to a file. Everything is fine at first, the first thread waits for the second to finish writing to the file before reading it. The two threads work happily, everything is fine as long as the writing thread always writes first.
    Solution code to this problem is:
    Code:
    #include <windows.h>
    #include <iostream>
    
    HANDLE hMutex, hWriteDone, hReadDone;
    int num, state;
    
    void Writer()
    {
    	for(int x=9; x>=0; x--)
    	{
    		while(true)
    		{
    			if (WaitForSingleObject(hMutex, INFINITE) == WAIT_FAILED)
    			{
    				std::cout<<"In writing loop, no mutex!\n";
    				ExitThread(0);
    			}
    			if (state == 0)
    			{
    				ReleaseMutex(hMutex);
    				WaitForSingleObject(hReadDone, INFINITE);
    				continue;
    			}
    			break;
    		}
    		std::cout<<"Write done\n";
    		num= x;
    		state= 0;
    		ReleaseMutex(hMutex);
    		PulseEvent(hWriteDone);
    	}
    }
    
    void Reader()
    {
    	while(true)
    	{
    		if (WaitForSingleObject(hMutex, INFINITE) == WAIT_FAILED)
    		{
    			std::cout<<"In reader, no mutex!\n";
    			ExitThread(0);
    		}
    		if (state == 1)
    		{
    			ReleaseMutex(hMutex);
    
    			WaitForSingleObject(hWriteDone, INFINITE);
    			continue;
    		}
    		if (num == 0)
    		{
    			std::cout<<"End of data\n";
    			ReleaseMutex(hMutex);
    			ExitThread(0);
    		}
    		else 
    		{
    			std::cout<<"Read done\n";
    			state=1;
    			ReleaseMutex(hMutex);
    			PulseEvent(hReadDone);
    		}
    	}
    }
    
    
    int main()
    {
    	HANDLE TName[2];
    	DWORD ThreadID;
    
    	state= 1;
    
    	hMutex= CreateMutex(NULL, FALSE, NULL);
    
    	hWriteDone= CreateEvent(NULL, TRUE, FALSE, NULL);
    	hReadDone= CreateEvent(NULL, TRUE, FALSE, NULL);
    
    	TName[0]= CreateThread(NULL, 0,
    	(LPTHREAD_START_ROUTINE)Writer,
    	NULL, 0, &ThreadID);
    
    	TName[1]= CreateThread(NULL, 0,
    	(LPTHREAD_START_ROUTINE)Reader,
    	NULL, 0, &ThreadID);
    
    	WaitForMultipleObjects(2, TName, TRUE, INFINITE);
    
    	CloseHandle(TName);
    }
    I realised that these problem are not the same, one is critical section problem sharing variable, other is solving race condition. But, I tried to think variable state as mutex in first example and didn't manage to make analogy. P(mutex) decrement int variable, and V(mutex) increment it. In the second example Writer function sets state to zero and Reader sets state to 1.
    Maybe I'm on the wrong track from the begining.
    I'm very new (start this morninig) to all this functions(WaitForSingle/MultipleObjects...etc), so
    I would ask if someone is kind to explain me on second example how this mechanism really works what is going on and how these functions doing such great job.

    I don't know if this is too much for a single thread on this forum, but you all helped me a lot before and hope will help me in future.

    Thanks in advance

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Multithreading (flag stopping a thread, ring buffer) volatile
    By ShwangShwing in forum C Programming
    Replies: 3
    Last Post: 05-19-2009, 07:27 AM
  2. The best place to learn
    By CougarElite in forum C Programming
    Replies: 15
    Last Post: 04-25-2004, 04:07 PM
  3. Novice trying to learn C++
    By dead in forum C++ Programming
    Replies: 10
    Last Post: 12-01-2003, 09:25 PM
  4. Multithreading
    By JaWiB in forum Game Programming
    Replies: 7
    Last Post: 08-24-2003, 09:28 PM
  5. Witch to learn first?
    By Unregistered in forum Windows Programming
    Replies: 2
    Last Post: 06-17-2002, 12:06 AM