I have 15 threads and I want to execute 10 functions I pushed. I do not care about protecting it now, just wonder why win api executes function, but std does not.
Code is more or less from handmade hero day 123
struct WorkQueueEntry
{
char* stringToPrint;
};
static uint32 nextEntryToDo;
static uint32 entryCount;
WorkQueueEntry entries[256];
inline void PushString(const char* string)
{
WorkQueueEntry* entry = entries + entryCount++;
entry->stringToPrint = const_cast<char*>(string);
}
struct ThreadInfo
{
int logicalThreadIndex;
};
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
printf("entry count %i, nextEntryToDo %i\n", entryCount, nextEntryToDo);
ThreadInfo* threadInfo = (ThreadInfo*)lpParameter;
for(;;) {
if(nextEntryToDo < entryCount) {
WorkQueueEntry* entry = entries + nextEntryToDo++;
char buffer[256];
sprintf_s(buffer, "Thread %u: %s", threadInfo->logicalThreadIndex, entry->stringToPrint);
printf(buffer);
}
}
}
somewhere in the main
#define WinThread
ThreadInfo threadInfo[5];
for(int i = 0; i < _ARRAYSIZE(threadInfo); ++i) {
ThreadInfo* info = threadInfo + i;
info->logicalThreadIndex = i;
#ifdef WinThread
{
DWORD threadID;
HANDLE threadHandle = CreateThread(0, 0, ThreadProc, info, 0, &threadID);
CloseHandle(threadHandle);
}
#else
{
std::thread t(ThreadProc, info);
t.join();
}
#endif
}
PushString("String 0\n");
PushString("String 1\n");
PushString("String 2\n");
PushString("String 3\n");
PushString("String 4\n");
PushString("String 5\n");
PushString("String 6\n");
PushString("String 7\n");
PushString("String 8\n");
PushString("String 9\n");
win api thread shows that at the begining of app entry count is 10, so if(nextEntryCount < entryCount)
is true and funciton can be done. Std thread has entry count 0 at the begining, so if(nextEntryCount < entryCount)
is not true and func cannot be done.
Why is that?
Pushing strings before creating std thread fixes it, but not exactly.
now it looks like this:
//#define WinThread
PushString("String 0\n");
PushString("String 1\n");
PushString("String 2\n");
PushString("String 3\n");
PushString("String 4\n");
PushString("String 5\n");
PushString("String 6\n");
PushString("String 7\n");
PushString("String 8\n");
PushString("String 9\n");
ThreadInfo threadInfo[5];
for(int i = 0; i < _ARRAYSIZE(threadInfo); ++i) {
ThreadInfo* info = threadInfo + i;
info->logicalThreadIndex = i;
#ifdef WinThread
{
DWORD threadID;
HANDLE threadHandle = CreateThread(0, 0, ThreadProc, info, 0, &threadID);
CloseHandle(threadHandle);
}
#else
{
std::thread t(ThreadProc, info);
t.join();
}
#endif
}
entry count is 10 at the begning and if(nextEntryCount < entryCount) is true, so func can be done, but it prints that work has been done by only thread with index of 0.
Why, using standard thread, only one thread has done all the work?