My First Multi-Threaded Code! What Do You Think?

Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved

Join Date: Oct 2008
Posts: 33
Reputation: f.ben.isaac is an unknown quantity at this point 
Solved Threads: 0
f.ben.isaac f.ben.isaac is offline Offline
Light Poster

My First Multi-Threaded Code! What Do You Think?

 
0
  #1
Apr 15th, 2009
I need to know how i did? Any review will be appreciated...

  1. /**program description:
  2. *
  3. * this simple program represents
  4. * the basic concept of threads.
  5. * main() process will create a
  6. * thread that calculate numbers
  7. * while main() output the results.
  8. * main() and threadProcess() share
  9. * share data from a same memory.
  10. * threadProcess() add two numbers
  11. * and dump the result into totalNumber.
  12. * On the other hand, main() uses
  13. * totalNumber to output the result.
  14. * Thus, totalNumber is the shared scope.
  15. * To avoid collision, i used mutex.
  16. *
  17. */
  18.  
  19. #include <iostream>
  20. #include <windows.h>
  21. using namespace std;
  22.  
  23. int totalNumber = 0;
  24. bool threadStarted = false;
  25.  
  26. HANDLE mutexHandle = NULL;
  27.  
  28. void threadProcess()
  29. {
  30. threadStarted = true;
  31.  
  32. for (int i=0; i < 10; i++)
  33. {
  34. WaitForSingleObject(mutexHandle, INFINITE);
  35.  
  36. cout<<"threadProcess() is calculating: "<<endl;
  37. totalNumber += i;
  38.  
  39. //make thread procedure in same
  40. //speed as main() process
  41. Sleep(10);
  42.  
  43. ReleaseMutex(mutexHandle);
  44. }
  45. }
  46.  
  47. int main()
  48. {
  49. mutexHandle = CreateMutex(NULL, false, NULL);
  50.  
  51. HANDLE threadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadProcess, NULL, 0, NULL);
  52.  
  53. //let thread starts first - main()
  54. //somewhat starts faster than the
  55. //spwaned process
  56. while(!threadStarted) { }
  57.  
  58. for(int i = 0; i < 10; i++)
  59. {
  60. WaitForSingleObject(mutexHandle, INFINITE);
  61.  
  62. cout<<"main() is giving out solution: "<<endl;
  63. cout<<totalNumber<<endl;
  64.  
  65. //make main() process run in same speed
  66. //with the created thread
  67. Sleep(10);
  68.  
  69. ReleaseMutex(mutexHandle);
  70. }
  71.  
  72. //wait for the thread to finish
  73. //in case its hanging around
  74. WaitForSingleObject(threadHandle, INFINITE);
  75. CloseHandle(mutexHandle);
  76.  
  77. cin.get();
  78. return 0;
  79. }
Last edited by f.ben.isaac; Apr 15th, 2009 at 1:14 am.
Reply With Quote Quick reply to this message  
Join Date: Mar 2009
Posts: 139
Reputation: MrSpigot is on a distinguished road 
Solved Threads: 33
MrSpigot's Avatar
MrSpigot MrSpigot is offline Offline
Junior Poster

Re: My First Multi-Threaded Code! What Do You Think?

 
0
  #2
Apr 15th, 2009
You should be pleased with your first attempt, it demonstrates threading nicely.
There are some criticisms I would make:
Your mutex isn't actually achieving much - totalNumber is only being updated by one thread. main() is just reading it, so no protection is necessary in this case. If you are using the mutex for synchronisation, well that isn't happening because each thread is releasing the mutex, then immediately trying to grab it again. You don't know which thread will get control.
What's the Sleep(10) for? If you are trying to ensure that control passes to the other thread it would be better placed after the ReleaseMutex() call. In any case, using Sleep() to try and synchronise threads is not a practical solution.
Just an idea, but why not try to implement this project using Events instead of a mutex. You could have an event for each thread to indicate when it has completed it's loop. Each thread checks the other thread's Event and proceeds when signalled. That would give you fully syncronised and more robust code (and a bit more practice ).
Reply With Quote Quick reply to this message  
Join Date: May 2008
Posts: 374
Reputation: Clockowl is on a distinguished road 
Solved Threads: 27
Clockowl's Avatar
Clockowl Clockowl is offline Offline
Posting Whiz

Re: My First Multi-Threaded Code! What Do You Think?

 
0
  #3
Apr 15th, 2009
Originally Posted by MrSpigot
main() is just reading it, so no protection is necessary in this case.
That's wrong, almost 100% sure, couldn't make sure with google, but it's just 2 threads trying to access the same memory: doesn't matter if they read or write, both will lead to errors.

Agreed on not using Sleep(). It's a useless function: wait for events to happen, don't guess how long such and such is going to take, and put that time in Sleep().
Reply With Quote Quick reply to this message  
Join Date: Mar 2009
Posts: 139
Reputation: MrSpigot is on a distinguished road 
Solved Threads: 33
MrSpigot's Avatar
MrSpigot MrSpigot is offline Offline
Junior Poster

Re: My First Multi-Threaded Code! What Do You Think?

 
1
  #4
Apr 15th, 2009
Originally Posted by Clockowl View Post
That's wrong, almost 100% sure, couldn't make sure with google, but it's just 2 threads trying to access the same memory: doesn't matter if they read or write, both will lead to errors.
Well I would appreciate you backing up a statement like that!
There are 2 threads here. One reads and writes (ie an addition), the other just reads. Two threads can indeed access the same memory quite happily (ok there might be some exceptions for custom embedded systems, but we're talking general purpose computers here). You have to remember that the operations in separate threads are not actually happening simultaneously, they are sequential at the hardware level and will not generate bad/corrupted data.
The write operation is atomic, you can't get half a write operation, so the read from the other thread will either get the value before or after the write. In this case it doesn't matter which it gets.
Of course, you do need to be aware of the operations you perform. Reading/writing a database in this way would not necessarily be atomic and possibly not safe.
Reply With Quote Quick reply to this message  
Join Date: Apr 2008
Posts: 160
Reputation: dmanw100 is on a distinguished road 
Solved Threads: 12
dmanw100's Avatar
dmanw100 dmanw100 is offline Offline
Junior Poster

Re: My First Multi-Threaded Code! What Do You Think?

 
0
  #5
Apr 15th, 2009
Where would a good place be to learn more about multithreading? I don't think there is much at www.cpluplus.com. Any suggestions on libraries/tutorials? Thanks!
Reply With Quote Quick reply to this message  
Join Date: May 2008
Posts: 374
Reputation: Clockowl is on a distinguished road 
Solved Threads: 27
Clockowl's Avatar
Clockowl Clockowl is offline Offline
Posting Whiz

Re: My First Multi-Threaded Code! What Do You Think?

 
0
  #6
Apr 15th, 2009
MrSpigot was 100% right, my bad. You don't need mutexes to write and read from one variable at the same time.

Tested with:

  1. #include <iostream>
  2. #include <windows.h>
  3. using namespace std;
  4.  
  5. int victim = 10;
  6.  
  7. void thread()
  8. {
  9. for(int n = 0; n < 99999999; n++){
  10. victim = n;
  11. }
  12. }
  13.  
  14. int main()
  15. {
  16.  
  17. HANDLE thread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread, NULL, 0, NULL);
  18. HANDLE thread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread, NULL, 0, NULL);
  19. HANDLE thread3 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread, NULL, 0, NULL);
  20.  
  21. WaitForSingleObject(thread1, INFINITE);
  22. WaitForSingleObject(thread2, INFINITE);
  23. WaitForSingleObject(thread3, INFINITE);
  24. return 0;
  25. }
Reply With Quote Quick reply to this message  
Join Date: Jul 2008
Posts: 2,001
Reputation: ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of ArkM has much to be proud of 
Solved Threads: 343
ArkM's Avatar
ArkM ArkM is offline Offline
Postaholic

Re: My First Multi-Threaded Code! What Do You Think?

 
0
  #7
Apr 15th, 2009
Originally Posted by MrSpigot View Post
Well I would appreciate you backing up a statement like that!
There are 2 threads here. One reads and writes (ie an addition), the other just reads. Two threads can indeed access the same memory quite happily (ok there might be some exceptions for custom embedded systems, but we're talking general purpose computers here). You have to remember that the operations in separate threads are not actually happening simultaneously, they are sequential at the hardware level and will not generate bad/corrupted data.
The write operation is atomic, you can't get half a write operation, so the read from the other thread will either get the value before or after the write. In this case it doesn't matter which it gets.
Of course, you do need to be aware of the operations you perform. Reading/writing a database in this way would not necessarily be atomic and possibly not safe.
>You have to remember that the operations in separate threads are not actually happening simultaneously
It's a wrong statement even for home desktop compiters with multicore processors.
>...and will not generate bad/corrupted data
It's a wrong statetement, especially referred to compound objects.
>The write operation is atomic, you can't get half a write operation...
It's a wrong statement, especially for string data, but for compound objects too. As usually, regular microprocessors provide atomic write operations only for 32-bit aligned words.
>In this case it doesn't matter which it gets
It's a wrong statement. How about corrupted program logic and erratical behaviour?..
>Reading/writing a database in this way would not necessarily be atomic and possibly not safe.
Most of modern database engines provide implicit transactions on SQL statement level so possibly it would be atomic...

Hmm...
Reply With Quote Quick reply to this message  
Join Date: May 2008
Posts: 374
Reputation: Clockowl is on a distinguished road 
Solved Threads: 27
Clockowl's Avatar
Clockowl Clockowl is offline Offline
Posting Whiz

Re: My First Multi-Threaded Code! What Do You Think?

 
0
  #8
Apr 15th, 2009
Okay, not 100% right. Darnit. xD

I've just created a single multithreaded program and it was (a dreaded task and) crashing constantly! So I ended up creating mutexes for every "group" of shared variables.
Reply With Quote Quick reply to this message  
Join Date: Mar 2009
Posts: 139
Reputation: MrSpigot is on a distinguished road 
Solved Threads: 33
MrSpigot's Avatar
MrSpigot MrSpigot is offline Offline
Junior Poster

Re: My First Multi-Threaded Code! What Do You Think?

 
0
  #9
Apr 15th, 2009
Originally Posted by ArkM View Post
>You have to remember that the operations in separate threads are not actually happening simultaneously
It's a wrong statement even for home desktop compiters with multicore processors.
>...and will not generate bad/corrupted data
It's a wrong statetement, especially referred to compound objects.
>The write operation is atomic, you can't get half a write operation...
It's a wrong statement, especially for string data, but for compound objects too. As usually, regular microprocessors provide atomic write operations only for 32-bit aligned words.
>In this case it doesn't matter which it gets
It's a wrong statement. How about corrupted program logic and erratical behaviour?..
>Reading/writing a database in this way would not necessarily be atomic and possibly not safe.
Most of modern database engines provide implicit transactions on SQL statement level so possibly it would be atomic...

Hmm...
I accept all that you're saying there, and good point about the multi-core processors, though even they would not cause a problem in this case. Regards the other statements you highlighted, did I really need to qualify everything by saying it was in the context of this post? I thought it was clear enough that strings/compound objects/corrupt logic etc were not under discussion. If anyone thought I was writing more generally, thanks for setting them straight.
Reply With Quote Quick reply to this message  
Join Date: May 2008
Posts: 374
Reputation: Clockowl is on a distinguished road 
Solved Threads: 27
Clockowl's Avatar
Clockowl Clockowl is offline Offline
Posting Whiz

Re: My First Multi-Threaded Code! What Do You Think?

 
0
  #10
Apr 15th, 2009
Originally Posted by MrSpigot
I accept all that you're saying there, and good point about the multi-core processors, though even they would not cause a problem in this case.
On my dualcore processor, 2 cores where in use and it indeed didn't give any errors as stated earlier. This is on Windows XP x64.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC