Julian
Julian

Reputation: 503

c++ semaphore is not considering order of call

I'm currently trying to limit currently running threads to an maximum amount, e.g. core-amount.

This is all doing well and I have something like 100 full data-writes (open, append, close) per second, but when not using the semaphore as mutex (with amount >1) the order or write-access is canged.

Using a for-loop:

    for(int i=0;i<10;i++)
            mywrite.writeasnewthread("test.txt","asd"+mywrite.tostring(i)); 

where writeasnewthread contains

    WaitForSingleObject(this->semaphor,INFINITE);
    CreateThread(NULL,0,&threadwrite,(void*)param,0,NULL);

with threadwrite the new thread, param containing name, data and the semaphore. Then in threadwrite at the end I call

    ReleaseSemaphore(writeparam->This->semaphor,1,NULL);

However, When I look at the file I wrote in threadwrite, there goes something on like

2013-5-16 14:41:25 asd0
2013-5-16 14:41:25 asd3
2013-5-16 14:41:25 asd5
2013-5-16 14:41:25 asd7
2013-5-16 14:41:25 asd1
2013-5-16 14:41:25 asd8
2013-5-16 14:41:25 asd9
2013-5-16 14:41:25 asd6
2013-5-16 14:41:25 asd4
2013-5-16 14:41:25 asd2

I probably have some basic misunderstanding how semaphores works, but I though the thread would be waiting for the semaphore to have a free slot again and then get worked on...

So, is there a nice way of preserving the order of the file? or would this destroy the concept of semaphores?

Regards, Julian

Upvotes: 3

Views: 749

Answers (2)

Michael Kohne
Michael Kohne

Reputation: 12044

A semaphore does NOT impose any relationship between the various threads that hold semaphores. It ONLY limits the number of entities that can successfully acquire the semaphore at a time.

There's nothing in the definition of a semaphore that has anything to do with thread scheduling. In your examples, the semaphores are operating properly.

If you want the writes in a particular order in the file, why use threads at all? Just do the writes from the main thread, in the order you want, and everything will be fine.

Threads are intended for use when you want things to happen in an undefined order. You can impose some ordering between the threads using mutexes, semaphores, fifos, and such, but if you want a strict one-after-the-other ordering of operations, you should probably not be using threads.

Upvotes: 5

Robert
Robert

Reputation: 2389

Well, simple answer is no. The OS is free to schedule the threads to execute in any order it likes, and it will most likely not be in the order you created them.

Upvotes: 6

Related Questions