943,617 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Marked Solved
  • Views: 729
  • C++ RSS
Apr 15th, 2009
0

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

Expand Post »
I need to know how i did? Any review will be appreciated...

C++ Syntax (Toggle Plain Text)
  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.
Similar Threads
Reputation Points: 46
Solved Threads: 0
Light Poster
f.ben.isaac is offline Offline
34 posts
since Oct 2008
Apr 15th, 2009
0

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

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 ).
Reputation Points: 76
Solved Threads: 40
Junior Poster
MrSpigot is offline Offline
156 posts
since Mar 2009
Apr 15th, 2009
0

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

Quote 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().
Reputation Points: 69
Solved Threads: 28
Posting Whiz
Clockowl is offline Offline
376 posts
since May 2008
Apr 15th, 2009
1

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

Click to Expand / Collapse  Quote originally posted by Clockowl ...
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.
Reputation Points: 76
Solved Threads: 40
Junior Poster
MrSpigot is offline Offline
156 posts
since Mar 2009
Apr 15th, 2009
0

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

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!
Reputation Points: 104
Solved Threads: 27
Posting Whiz in Training
dmanw100 is offline Offline
239 posts
since Apr 2008
Apr 15th, 2009
0

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

MrSpigot was 100% right, my bad. You don't need mutexes to write and read from one variable at the same time.

Tested with:

cpp Syntax (Toggle Plain Text)
  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. }
Reputation Points: 69
Solved Threads: 28
Posting Whiz
Clockowl is offline Offline
376 posts
since May 2008
Apr 15th, 2009
0

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

Click to Expand / Collapse  Quote originally posted by MrSpigot ...
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...
Reputation Points: 1234
Solved Threads: 347
Postaholic
ArkM is offline Offline
2,001 posts
since Jul 2008
Apr 15th, 2009
0

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

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.
Reputation Points: 69
Solved Threads: 28
Posting Whiz
Clockowl is offline Offline
376 posts
since May 2008
Apr 15th, 2009
0

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

Click to Expand / Collapse  Quote originally posted by ArkM ...
>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.
Reputation Points: 76
Solved Threads: 40
Junior Poster
MrSpigot is offline Offline
156 posts
since Mar 2009
Apr 15th, 2009
0

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

Quote 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.
Reputation Points: 69
Solved Threads: 28
Posting Whiz
Clockowl is offline Offline
376 posts
since May 2008

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: random-access files
Next Thread in C++ Forum Timeline: c++ problem need help pls





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC