windows Thread Synchronization

Use WaitForSingleObject function & WaitForMultipleObjects function

#include <stdio.h>
#include <windows.h>
#include <process.h>
unsigned WINAPI ThreadFunc(void *arg); int main(int argc, char *argv[]) { HANDLE hThread; DWORD wr; unsigned threadID; int param = 5; hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc, (void *)&param, 0, &threadID); if((wr = WaitForSingleObject(hThread, INFINITE)) == WAIT_FAILED) { puts("thread wait error"); return -1; } printf("wait result: %s \n", (wr == WAIT_OBJECT_0) ? "signaled" : "time-out"); puts("end of main"); return 0; } unsigned WINAPI ThreadFunc(void *arg) { int i; int cnt = *((int *)arg); for(i = 0; i < cnt; i ++) { Sleep(1000); puts("running thread"); } return 0; }

  

#include <stdio.h>
#include <windows.h>
#include <process.h>
 
 
#define NUM_THREAD 50
unsigned WINAPI threadInc(void *arg);
unsigned WINAPI threadDec(void *arg);
long long num = 0;
 
 
int main(int argc, char *argv[])
{
    HANDLE  tHandles[NUM_THREAD];
    int i;
 
 
    printf("sizeof long long: %d \n", sizeof(long long));
    for(i = 0; i < NUM_THREAD; i ++)
    {
        if(i % 2)
            tHandles[i] = (HANDLE)_beginthreadex(NULL, 0, threadInc, NULL, 0, NULL);
        else
            tHandles[i] = (HANDLE)_beginthreadex(NULL, 0, threadDec, NULL, 0, NULL);
    }
 
 
 
 
    WaitForMultipleObjects(NUM_THREAD, tHandles, TRUE, INFINITE);
    printf("result: %lld \n", num);
    return 0;
}
 
 
unsigned WINAPI threadInc(void *arg)
{
    int i;
    for(i = 0; i < 50000000; i ++)
        a + = 1;
    return 0;
}
 
 
unsigned WINAPI threadDec(void *arg)
{
    int i;
    for(i = 0; i < 50000000; i ++)
        a - = 1;
    return 0;
}

  

Guess you like

Origin www.cnblogs.com/wisdomroc/p/11842685.html