Please help me. I need to know how to write a simple multithreaded program. Thank you
Please help me. I need to know how to write a simple multithreaded program. Thank you
Geez, ever heard of a search feature?
Or do you want a complete spoon-fed answer because you're too helpless to do any actual work yourself?
Nevermind - don't bother answering unless you have something useful to say....
Bah
This can be more difficult than you might think. And yes, I have searched, and instead of posting that mean reply, you could have given me a link at least, Thanks anyway
this is a sample, can't remember where i got it -_-"
it use _beginthread() function which is included in C run-time libraries. you can get more details on msdn.
Code:#include <windows.h> #include <process.h> #include <iostream> using namespace std; void Func1(void *); void Func2(void *); CRITICAL_SECTION Section; int main() { InitializeCriticalSection(&Section); _beginthread(Func1, 0, NULL); _beginthread(Func2, 0, NULL); Sleep(10000); DeleteCriticalSection(&Section); cout << "Main exit" << endl; return 0; } void Func1(void *P) { int Count; for (Count = 1; Count < 11; Count++) { EnterCriticalSection(&Section); cout << "Func1 loop " << Count << endl; LeaveCriticalSection(&Section); } return; } void Func2(void *P) { int Count; for (Count = 10; Count > 0; Count--) { EnterCriticalSection(&Section); cout << "Func2 loop " << Count << endl; LeaveCriticalSection(&Section); } return; } int main() { HANDLE hThreads[2]; InitializeCriticalSection(&Section); hThreads[0] = (HANDLE)_beginthread(Func1, 0, NULL); hThreads[1] = (HANDLE)_beginthread(Func2, 0, NULL); WaitForMultipleObjects(2, hThreads, TRUE, INFINITE); DeleteCriticalSection(&Section); cout << "Main exit" << endl; return 0; }
blow me ... ...
Thank you very much. I'll try and see.
Ok I tried. But it says _beginthread can't be found. And I am using visual studio 2003. I also tried the code on digital mars. And anyway, why are there two declarations of main()? thank you in advance
It looks like a mistake. They are just two different ways to handle things. The first main() is sleeping for 10 seconds and assuming that both threads have exited by the time the wait expires. The second main() is getting a handle to each thread, and explicitly waiting for both threads to exit before continuing. Take your pick and comment the other one out. As far as the linker not finding _beginthread, you need to compile with /MT. Since you have visual studio 2003, why not click on help->index, type in _beginthread, and look at the example code that they give you for free. Just a thought.
The crows maintain that a single crow could destroy the heavens. Doubtless this is so. But it proves nothing against the heavens, for the heavens signify simply: the impossibility of crows.
Yup, exactly what I did. Thank you very much.