Click to See Complete Forum and Search --> : thread sync


sccx
March 28th, 2006, 10:38 PM
Like to get 123412341234... as output fastest and safest way possible. How to do it with createsemaphore/or any other fastest way using two threads to obtain 12121212... as output?
#include <afxmt.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <process.h>

void main(void);
void Thread1();
void Thread2();
void Thread3();
void Thread4();

static HANDLE mutexHandle = NULL;

void main(void)
{

HANDLE thread1;
HANDLE thread2;
HANDLE thread3;
HANDLE thread4;

mutexHandle = CreateMutex(NULL, false, NULL);

thread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Thread1, NULL, 0, NULL);
Sleep(100);
thread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Thread2, NULL, 0, NULL);
Sleep(100);
thread3 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Thread3, NULL, 0, NULL);
Sleep(100);
thread4 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Thread4, NULL, 0, NULL);
Sleep(100);

while(1)
{}
}

void Thread1()
{
printf("1");
WaitForSingleObject(mutexHandle, INFINITE);
ReleaseMutex(mutexHandle);
Thread1();
}

void Thread2()
{
printf("2");
WaitForSingleObject(mutexHandle, INFINITE);
ReleaseMutex(mutexHandle);
Thread2();
}

void Thread3()
{
printf("3");
WaitForSingleObject(mutexHandle, INFINITE);
ReleaseMutex(mutexHandle);
Thread3();
}

void Thread4()
{
printf("4");
WaitForSingleObject(mutexHandle, INFINITE);
ReleaseMutex(mutexHandle);
Thread4();
}

wildfrog
March 29th, 2006, 06:37 PM
Here's an example using multiple threads, event objects and SignalObjectAndWait to perform synchronization... no error checking or cleanup..

#define _WIN32_WINNT 0x0400
#include <windows.h>
#include <iostream>

struct ThreadData
{
int current;
int next;
HANDLE* events;
};

DWORD WINAPI ThreadProc(LPVOID lp)
{
ThreadData* pData = (ThreadData*) lp;

// wait for our turn
WaitForSingleObject(pData->events[pData->current], INFINITE);
while (true)
{
// print value (current is zero based so add 1)
std::cout << (pData->current + 1) << std::endl;

// signal next event then wait for our turn
SignalObjectAndWait(pData->events[pData->next], pData->events[pData->current], INFINITE, false);
}
}

int _tmain(int argc, _TCHAR* argv[])
{
// How many threads do we need?
const int THREAD_COUNT = 6;

// create events
HANDLE events[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; ++i)
events[i] = CreateEvent(NULL, false, false, NULL);

// create thread data
ThreadData data[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; ++i)
{
data[i].current = i;
data[i].next = (i + 1) % THREAD_COUNT;
data[i].events = events;
}

// create threads
HANDLE threads[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; ++i)
threads[i] = CreateThread(NULL, 0, ThreadProc, &data[i], 0, NULL);

// signal the first event and the rest will follow
SetEvent(events[0]);

Sleep(5000);

return 0;
}