Call a function from a thread and RS 232 - c++

I am programming in Visual Studio 2008 in console application. I am working with a display that is communicated by Rs 232.
I have a thread that counts from 0 to 10 seconds. When reaches 10 I want to turn off the displays backlight. For that I have a function that is called from the thread. The called from the thread is well because I know that the code of the function is executed.
But code of turning the backlight off does not work when the function is called from the thread and it works the it is called from another place. Any ideas?
Thanks.
void FunctionBacklightoff(HANDLE portHandle,DWORD bytesTransmitted)
{
cout << "backoff";
WriteFile(portHandle, backlight_off , 4, &bytesTransmitted, NULL);//does not work when
//it is called from the thread. It works when it is called from wmain()
}
DWORD WINAPI solo_thread(void* arg)
{
int Counter = 0;
printf( "In second thread...\n" );
while ( true )
{
if(Counter<10)
{
Counter++;
Sleep(1000);
}
else
{
printf( "Han pasado 10 segundos; Counter:-> %d\n", Counter );
FunctionBacklightoff(portHandle,bytesTransmitted);//from here doesnt work
Counter = 0;
}
}
return 0;
}
int wmain(void)
{
hThread =CreateThread(NULL, 0, solo_thread,NULL ,0, NULL);
//inicialize rs232 communications...
retVal = PortOpen(&portHandle, 115200);
if (!retVal)
{
printf("Could not open CoM port");
getchar();
}
else
{
printf("CoM port opened successfully");
retVal = FALSE;
}
FunctionBacklightoff(portHandle,bytesTransmitted);//from here works
}

How portHandle is declared? Looks like it's static field so thread could simply not get change that happen after it's creation. To be sure you could mark portHandle as volatile or change the order of operations:
//Open port so we will be sure that postHandle is populated before thread starts.
retVal = PortOpen(&portHandle, 115200);
hThread = CreateThread(NULL, 0, solo_thread,NULL ,0, NULL);
Also you have a BUG that your wmain will exit before thread being executed. To fix that you should place following code right before wmain last bracket:
WaitForSingleObject(hThread, INFINITE);
Note that because your thread have while(true) without break condition it will run forever and each 10 seconds will switch off backlight. If this was not intentional add a break into else.

Related

QueueUserAPC function not working, reporting error 31 randomly

The following code uses the QueueUserAPC function to add commands to a dispatcher thread in order to synchronize console output.
#include <Windows.h>
#include <iostream>
constexpr auto fenceName = L"GlobalFence";
constexpr auto dispatchCloser = L"GlobalDispatchStop";
constexpr int threadCount = 5;
DWORD WINAPI pure(LPVOID lpThreadParameter)
{
const HANDLE dispatchCloseEvent = OpenEventW(EVENT_ALL_ACCESS, FALSE, dispatchCloser);
while(WaitForSingleObjectEx(dispatchCloseEvent, INFINITE, TRUE) != WAIT_IO_COMPLETION)continue;
return 0;
}
HANDLE dispatcher;
int main()
{
const HANDLE dispatchCloseEvent = CreateEventW(nullptr, TRUE, FALSE, dispatchCloser);
dispatcher = CreateThread(NULL, 1024, &pure, 0, 0, NULL);
const HANDLE g_FenceEvent = CreateEventW(nullptr, TRUE, FALSE, fenceName);
HANDLE threads[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = CreateThread(NULL, 1024*1024,
[](LPVOID) -> DWORD
{
DWORD d = QueueUserAPC(([](ULONG_PTR) {std::cout << "thread opened\n"; }), dispatcher, NULL);
if(d == 0)std::cout << GetLastError() << std::endl;
HANDLE a = OpenEventW(EVENT_ALL_ACCESS, FALSE, fenceName);
WaitForSingleObject(a, INFINITE);
d = QueueUserAPC([](ULONG_PTR) {std::cout << "thread released\n"; }, dispatcher, NULL);
if (d == 0)std::cout << GetLastError() << std::endl;//often reports error 31
return 0;
},
0, 0, NULL);
}
Beep(300, 300);//the length of the delay effects the behavior, somehow.
SetEvent(g_FenceEvent);
SetEvent(dispatchCloseEvent);
WaitForMultipleObjects(threadCount, threads, TRUE, INFINITE);
WaitForSingleObject(dispatcher, INFINITE);
SetEvent(dispatchCloseEvent);
for (int i = 0; i < threadCount; i++)
CloseHandle(threads[i]);
CloseHandle(g_FenceEvent);
CloseHandle(dispatchCloseEvent);
}
The code executes correctly about 40% of the time. Sometimes (although this is somewhat rare) the "thread opened" text won't get written to the console the right amount of times, but no error is reported from getLastError()
As soon as the loop in pure() receives its 1st APC notification, the loop breaks and pure() exits, terminating the thread.
Error 31 is ERROR_GEN_FAILURE, and per the QueueUserAPC() documentation:
When the thread is in the process of being terminated, calling QueueUserAPC to add to the thread's APC queue will fail with (31) ERROR_GEN_FAILURE.
If you expect the dispatcher thread to process more than one APC notification, it needs to stay running. You meant to use == instead of != in your loop condition:
while (WaitForSingleObjectEx(dispatchCloseEvent, INFINITE, TRUE) == WAIT_IO_COMPLETION) continue;
That way, if the wait exits due to a queued APC, the loop will go back to waiting for the next APC. The loop will break, exiting pure() to terminate the thread, only when it receives a return value other than an APC notification, such as WAIT_OBJECT_0 when the close event is signaled.
Another problem I see is that you are signaling dispatchCloseEvent too soon, so the dispatcher thread can stop running while the fenced threads are still trying to queue APCs to it. That is why the 2nd call to QueueUserAPC() in each fenced thread fails randomly. You need to wait for all of the fenced threads to finish first, THEN signal the dispatcher to stop running.
SetEvent(g_FenceEvent);
WaitForMultipleObjects(threadCount, threads, TRUE, INFINITE);
SetEvent(dispatchCloseEvent); // <-- move here!
WaitForSingleObject(dispatcher, INFINITE);
Also, all of your threads are leaking the HANDLEs they open with OpenEventW(). You need to call CloseHandle() on them, per the OpenEventW() documentation:
Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The event object is destroyed when its last handle has been closed.
For that matter, you don't really need OpenEventW() at all. You can pass the existing HANDLEs from main() to each thread via their LPVOID parameter instead:
DWORD WINAPI pure(LPVOID lpThreadParameter)
{
HANDLE dispatchCloseEvent = (HANDLE) lpThreadParameter;
...
return 0;
}
CreateThread(..., &pure, dispatchCloseEvent, ...);
CreateThread(...,
[](LPVOID param) -> DWORD
{
HANDLE a = (HANDLE) param;
...
},
g_fenceEvent, ...);
Or, just use global variables instead.
Either way, with OpenEventW() eliminated, there is no more need to assign names to your events when calling CreateEventW(), thus no longer exposing them to potential interference from outside code.
Also, you are also not closing the dispatcher thread's HANDLE either, like you are closing the fenced threads' HANDLEs.

Why does GetExitCodeThread() return FALSE here?

I have a small test code. My assumption is in below code, since I didn't set flag to stop the thread, then in the line of GetExitCodeThread(). it should return TRUE and return code is STILL_ACTIVE.
While in actual test, the result is:
Every time, the return value of GetExitCodeThread() is FALSE, so in main(), the while loop never entered. Could somebody please tell me the reason? What's wrong in my code. Thanks.
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "afxwin.h"
bool bExit = false;
HANDLE hOriginalThread;
static UINT ThreadFunc(LPVOID pParam)
{
int iCount = 0;
printf("start thread--ThreadFunc\n");
printf("Thread loop start: --ThreadFunc");
while (!bExit)
{
iCount++;
if (iCount % 50 == 0)
printf(".");
}
printf("Thread loop end: %d--ThreadFunc\n", iCount++);
printf("end thread--ThreadFunc\n");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
hOriginalThread = AfxBeginThread(ThreadFunc, (LPVOID)0, THREAD_PRIORITY_NORMAL, 0, 0);
Sleep(500);
DWORD dwEC;
int iTry = 0;
BOOL bStatus;
bStatus = GetExitCodeThread(hOriginalThread, &dwEC);
if (!bStatus)
{
printf("error GetExitCodeThread: %d--Main\n", GetLastError());
}
while (bStatus && dwEC == STILL_ACTIVE)
{
printf("Check Thread in active: %d--Main\n", iTry);
Sleep(1);
iTry++;
if (iTry>5)
{
printf("Try to terminate Thread loop: %d--Main\n", iTry++);
TerminateThread(hOriginalThread, 0);// Force thread exit
}
bStatus = GetExitCodeThread(hOriginalThread, &dwEC);
}
hThread = NULL;
printf("End Main --Main\n");
return 0;
}
AfxBeginThread() returns a CWinThread* object pointer, not a Win32 HANDLE like CreateThread() does. So GetExitCodeThread() fails due to an invalid thread handle, which GetLastError() should have told you.
CWinThread has an operator HANDLE() to get the proper Win32 handle of the thread, eg:
CWinThread *pThread = AfxBeginThread(...);
if (!pThread) ... // error handling
hOriginalThread = *pThread;
The reason your code even compiles is because you are likely not compiling with STRICT Type Checking enabled, so HANDLE is just a simple void*, which any kind of pointer can be assigned to. If you enable STRICT, HANDLE will not be void* and assigning the return value of AfxBeginThread() directly to hOriginalThread will cause a compiler error due to a type incompatibility.

Why semaphore is released but WaitForSingleObject() still stuck?

UPDATE: I found that the semaphore they are releasing is not the semaphore the monitor thread is waiting! I used cout<<ready to find the semaphore the threads are releasing is 00000394, which is not the handle of the semaphore the monitor thread is waiting for. What is the possible reason for this problem? Thank you!
I am new to multithread programming in Windows. Today when I'm writing my online game server, I try to use semaphores in Windows. It is written based on IOCP so that every message is handled in a separate thread. A game consists 4 players.
What I expect it to do is: when receiving a message, a new thread starts and release a ready. There is a monitor thread waiting for 4 ready, and then releases 4 all_ready. Each thread waits one all_ready and goes on.
The code is here:
CGameHost is a manager for a 4-player game.
CGameHost::CGameHost(void)
{
init_times=0;
ready = CreateSemaphore(NULL, 0, 4, NULL);
read = CreateSemaphore(NULL, 0, 4, NULL);
all_ready = CreateSemaphore(NULL, 0, 4, NULL);
all_read = CreateSemaphore(NULL, 0, 4, NULL);
monitor_thread = (HANDLE)_beginthreadex(NULL, 0, Monitor, (LPVOID)this, NULL, 0);
}
unsigned __stdcall CGameHost::Monitor( LPVOID p ) // a static function
{
CGameHost *nowp = (CGameHost *)p;
while(true)
{
int i;
for(i=1;i<=MAX_PLAYER;i++)
{
WaitForSingleObject(nowp->ready, INFINITE);//stuck here
cout<<"Get Ready!"<<endl; // This is not outputed, which means it stucks in the last row.
}
for(i=1;i<=MAX_PLAYER;i++)
{
ReleaseSemaphore(nowp->all_ready, 1, NULL);
}
for(i=1; i<=MAX_PLAYER; i++)
{
WaitForSingleObject(nowp->read, INFINITE);
}
for(i=1; i<=MAX_PLAYER;i++)
{
ReleaseSemaphore(nowp->all_read, 1, NULL);
}
}
return 0;
}
void CGameHost::ReleaseReady()
{
ReleaseSemaphore(ready, 1, NULL);
}
void CGameHost::WaitAllReady()
{
WaitForSingleObject(all_ready, INFINITE);
}
void CGameHost::ReleaseRead()
{
ReleaseSemaphore(read, 1, NULL);
}
void CGameHost::WaitAllRead()
{
WaitForSingleObject(all_read, INFINITE);
}
DataProcess::Game is the message handler for incoming game messages.
CMessage Dataprocess::Game( CMessage* recv_msg )
{
CMessage ret;
int now_roomnum = recv_msg->para1;
int now_playernum = recv_msg->para2;
if(true)
{
cout<<"Received Game Message: "<<endl;
cout<<"type2 = "<<recv_msg->type2;
cout<<" player_num = "<<now_playernum<<" msg= "<<recv_msg->msg<<endl;
}
if(recv_msg->type2 == MSG_GAME_OPERATION)
{
ret.type1 = MSG_GAME;
ret.type2 = MSG_GAME_OPERATION;
cout<<"Entered from "<<now_playernum<<endl;
game_host[now_roomnum].SetMessage(now_playernum, recv_msg->msg);
game_host[now_roomnum].ReleaseReady();
cout<<"Released Ready from "<<now_playernum<<endl;//this is shown
game_host[now_roomnum].WaitAllReady();//stuck here
cout<<"AllReady from"<<now_playernum<<endl;//not shown
}
return ret;
}
Your reply will be of great help for a beginner of Windows multithread programmer like me! Thank you!
If I understood your needs, you should probably have something like this..
HANDLE hPlayersReady[4];
HANDLE hAllPlayed;
Create these 5 events, and then on your monitor thread,
do something like this...
while(true)
{
// Wait for all players to move
WaitForMultipleObjects(4, &hPlayersReady, true, INFINITE);
// Process move
...
// Advise players the move was processed...
SetEvent(hAllPlayed);
}
And on your player thread X
while(true)
{
// Make my move
...
// Advise monitor I'm ready
SetEvent(hPlayersReady[X]);
// Wait for ready to do another move
WaitForSingleObject(hAllPlayed);
}
Well, I solved it myself. The reason is that I used CreateSemaphore again after creating the thread, making the player thread visiting different semaphores as the monitor thread... Sorry for my stupidness, and thank you for telling me so much!

Asynchronous Procedure Calls

I'm trying to get APC to work in my C++ code but I fail. I'm lost for words. In C# it works all fine (logically the same code). I want thread 2 to inject a call into thread 1. But in my C++ project it wont execute for some reason. What am I doing wrong ?
thread 1 (main thread)
thread 2 (sub thread, that needs the main thread to execute a function)
Code:
#include "stdio.h"
#include "windows.h"
#define TIME 2500
#define LAST_ERROR printf("last error: %i\r\n", GetLastError());
HANDLE handle1, handle2;
void ThreadInfo(char* prefix = "")
{
printf("%sthread id: %i\r\n", prefix, GetCurrentThreadId());
}
VOID CALLBACK apc( _In_ ULONG_PTR data)
{
ThreadInfo(" -> apc: 2 -> 1: ");
}
void run1()
{
while (true)
{
Sleep(TIME);
ThreadInfo("1: ");
// apc
//QueueUserAPC(apc, handle2, (ULONG_PTR) NULL);
}
}
void run2()
{
while (true)
{
Sleep(TIME);
ThreadInfo("2: ");
// apc
QueueUserAPC(apc, handle1, (ULONG_PTR) NULL);
}
}
void TestThreads()
{
DWORD threadId;
SECURITY_ATTRIBUTES a;
a.nLength = 12;
a.lpSecurityDescriptor = NULL;
a.bInheritHandle = 1;
DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &handle1, 0, true, 2);
LAST_ERROR
handle2 = CreateThread(NULL, 100000, (LPTHREAD_START_ROUTINE)run2, NULL, 0, &threadId);
printf("handles (1, 2): %i, %i\r\n", handle1, handle2);
printf("ids (1, 2): %i, %i\r\n", threadId, GetCurrentThreadId());
printf("--------------------------------\r\n");
run1();
}
int main()
{
TestThreads();
printf("done.");
getchar();
return 0;
}
Sleep(TIME);
That's your problem statement. APCs are pretty dangerous, they permit code re-entrancy. The rough equivalent to the infamous Application.DoEvents() statement that got so many VB programmers in trouble. Windows doesn't just let them run, you have to be explicit that your code is re-entrant so that the APC can safely run without screwing up your program state.
The specific requirement is that your thread is in an "alertable wait state". Getting into a wait state is not the issue, the Sleep() call does that. It is however not an alertable state. You have to use this instead:
SleepEx(TIME, TRUE);
Modify the run1() function in your test program and you'll now see the APC callback getting called. Compare to GetOverlappedResultEx(), SignalObjectAndWait(), WaitForSingleObjectEx() and WaitForMultipleObjectsEx(), other winapi calls that can put a thread in an alertable wait state. And yes, Thread.Sleep() in a managed program is alertable, the CLR calls SleepEx() under the hood.

C++ thread termination with waiting window

So, the code goes somehow like this:
MAIN(){
/*waiting window class declaration*/
threadinfo* oThread=new threadinfo(); //An object that will help me know when to finish the thread
QueueUserWorkItem((LPTHREAD_START_ROUTINE)waitingWindow, (void*)mThread, WT_EXECUTELONGFUNCTION);
function_that_takes_time();
oThread->setTerminated(); //set member terminated to bool true
/*continue with other things*/
}
and waitingWindow function that will run on that thread
MSG msg;
hwndWaiting=CreateWindow(...) // here the window is created
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, null, 0U, 0U, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
if(oThread->isTerminated()) // isTerminated returns bool true if terminated
{
delete oThread;
ExitThread(0);
}
}
}
ExitThread(0);
Is ExitThread a good way to remove the waiting window, and safely remove the thread? (at least I'm 100% sure this way when to end it).
I'm asking this because this works nice in Windows XP, but will crash with "the application has stopped working" on Windows 7.
Thanks for the help.
The best way to end threads in general, is to let them "gracefully" finish up by themselves. You could tell the thread to end by setting an event, for example:
HANDLE hevent_die = CreateEvent(...);
HANDLE hthread_something = CreateThread(...); // or _beginthread()
...
DWORD WINAPI thread_func (LPVOID param)
{
while(working && WaitForSingleObject(hevent_die, 0)!=WAIT_OBJECT_0)
{
...
}
return 0;
}
while (msg.message != WM_QUIT)
{
...
if(WaitForSingleObject(hthread_something, 0) == WAIT_OBJECT_0)
{
// do things if needed
}
}
SetEvent(hevent_die);
WaitForSingleObject(hthread_something, INFINITE);
CloseHandle(hthread_something);
CloseHandle(hevent_die);
hthread_something = 0;
hevent_die = 0;
If you are using nested loops inside the thread function, they too will have to end if they receive the event.
You should exit your loop and thread cleanly so that any destructors are called correctly. Don't use ExitThread(), just use a flag to indicate when to exit the loop and then just exit your waitingWindow function at the end.