Do not use the mutex two-thread output array arr
# Include <string> <br/> # include <iostream> <br/> # include <windows. h> <br/> using namespace STD; </P> <p> handle hmutex = NULL; <br/> int arr [5] = {1, 2, 3, 4, 5 }; </P> <p> DWORD callback thread1 (lpvoid PARAM) <br/>{< br/> while (true) <br/>{< br/> // waitforsingleobject (hmutex, infinite); </P> <p> cout <"thread1:/t "; <br/> for (INT I = 0; I <5; I ++) <br/>{< br/> cout <arr [I] <''; <br/> sleep (50); <br/>}< br/> cout <Endl; </P> <p> // releasemutex (hmutex ); <br/>}</P> <p> DWORD callback thread2 (lpvoid PARAM) <br/>{< br/> while (true) <br/>{< br/> // waitforsingleobject (hmutex, infinite); </P> <p> cout <"thread2:/t "; <br/> for (INT I = 0; I <5; I ++) <br/>{< br/> cout <arr [I] <''; <br/> sleep (50); <br/>}< br/> cout <Endl; </P> <p> // releasemutex (hmutex ); <br/>}</P> <p> int main () <br/>{< br/> // hmutex = createmutex (null, null, null); <br/> createthread (null, 0, thread1, null); <br/> createthread (null, 0, thread2, null, null, null); <br/> while (true) <br/>{< br/> sleep (100); <br/>}< br/> return 0; <br/>}< br/>
Result:
Use mutex output:
Handle winapi createmutex (
_ In lpsecurity_attributes{
Showtip (this)
} "> Lpmutexattributes,
_ In bool{
Showtip (this)
} "> Binitialowner,
_ In lpctstr{
Showtip (this)
} "> Lpname
);
DWORD winapi waitforsingleobject (
_ In handle{
Showtip (this)
} "> Hhandle,
_ In DWORD{
Showtip (this)
} "> Dwmilliseconds
);
TheWaitforsingleobjectFunction can wait for the following objects:
- Change Notification
- Console input
- Event
- Memory resource notification
- Mutex
- Process
- Semaphore
- Thread
- Waitable Timer
The main thread uses waitforsingleobject to wait for the end of another thread:
# Include <string> <br/> # include <iostream> <br/> # include <windows. h> <br/> using namespace STD; </P> <p> int arr [5] = {1, 2, 3, 4, 5 }; </P> <p> DWORD callback thread1 (lpvoid PARAM) <br/> {<br/> for (int c = 0; C <10; C ++) <br/> {<br/> cout <"thread1:/t"; <br/> for (INT I = 0; I <5; I ++) <br/>{ <br/> cout <arr [I] <''; <br/> sleep (50 ); <br/>}< br/> cout <Endl; <br/>}< br/> return 0; <br/>}</P> <p> handle hthread1 = NULL; <br/> int main () <br/>{< br/> hthread1 = createthread (null, 0, thread1, null); <br/> waitforsingleobject (hthread1, infinite); <br/> return 0; <br/>}< br/>