ホームに戻る
 15、(コードサンプル)スレッドとミューテックス

// bcc32 -WM *.cpp

#include <windows.h>
#include <process.h>
#include <stdio.h>

#define MUTEX_STRING "mutex_string"

void thread(void *d);

HANDLE hMutex;

int main()
{
  int i, d = 0;
  HANDLE hThread[5];

  hMutex = CreateMutex(NULL, FALSE, MUTEX_STRING);

  if(!hMutex || (GetLastError() == ERROR_ALREADY_EXISTS)){
    getchar();
    return 1;
  }

  for(i = 0; i < 5; i++){
    hThread[i] = (HANDLE)_beginthread(thread, 0, &d);
  }

  for(i = 0; i < 5; i++){
    WaitForSingleObject(hThread[i], INFINITE);
    printf("end  :%d\n", i);
  }

  Sleep(3000);

  CloseHandle(hMutex);

  return 0;
}

void thread(void *d)
{
  int d1;

  WaitForSingleObject(hMutex, INFINITE);

  d1 = (*(int *)d)++;

  printf("start:%d\n", d1);

  Sleep(1000);

  ReleaseMutex(hMutex);

  _endthread();
}

inserted by FC2 system