runtime error in thread in c++ - c++

Getting runtime error in thread, error is "Unhandled exception at 0x0043e98e in clientCheck.exe: 0xC0000005: Access violation reading location 0x025042c4".
//create thread in cpp file
CreateThread(NULL,0,stayConnectedAtClient,this,0,NULL);
//thread definition in header file
static unsigned long __stdcall stayConnectedAtClient(void *i_socketTransPortClient){
((SocketTransportClient*)i_socketTransPortClient)->stayConnectedThread();
return 0;
}
//thread function defination in cpp file
void RMLThinTransport::SocketTransportClient::stayConnectedThread()
{
Sleep(20000);
OutputDebugStringW(L"this is stayconnected thread");
while(m_tryToConnect) // get error here, not getting value of m_tryToConnect it is Boolean and declared in class.
{
if(!m_isConnected) // m_isConnected value is also not updated even if it is changed by other function
{
break;
}
/* sleep for period of time given in configuration file */
Sleep(m_stayConnected);
if(!m_allreadyConnected)
{
bool isConnect=Connect();
if(isConnect)
{
m_allreadyConnected=true;
}
OutputDebugStringW(L"isConnect false");
}
}
}
all values are updated in method disconnect.
bool RMLThinTransport::SocketTransportClient::disconnect()
{
m_isConnected=false;
m_tryToConnect=false;
notifyUserConnected(m_isConnected);
if(m_socketClient!=INVALID_SOCKET)
{
shutdown(m_socketClient,SD_BOTH);
closesocket(m_socketClient);
m_socketClient=INVALID_SOCKET;
}
Sleep(3000);
return false;
}
bool RMLThinTransport::SocketTransportClient::Connect()
{
try
{
m_socketClient = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
if(m_socketClient==INVALID_SOCKET){
int lastError;
lastError=WSAGetLastError();
SocketExceptions exceptionInOpenSocket;
exceptionInOpenSocket.detectErrorOpenSocket(&lastError);
throw exceptionInOpenSocket;
}
}
catch(SocketExceptions& i_exceptionInOpenSocket)
{
throw i_exceptionInOpenSocket;
return false;
}
memset(&m_SocketAddressIn,0,sizeof(m_SocketAddressIn));
m_SocketAddressIn.sin_family=AF_INET;
m_SocketAddressIn.sin_addr.s_addr=inet_addr(m_ccIPAddress);
m_SocketAddressIn.sin_port=htons(m_portNumber);
try
{
if(SOCKET_ERROR==connect(m_socketClient,(SOCKADDR *)&m_SocketAddressIn,sizeof(m_SocketAddressIn)))
{
m_allreadyConnected=false;
int lastErrorCode=WSAGetLastError();
SocketExceptions exceptionInConnection;
exceptionInConnection.detectErrorConnect(&lastErrorCode);
throw exceptionInConnection;
}
else
{
setConnected(true);
m_allreadyConnected=true;
if(m_evesdropString!=""){
char* charbuf=new char[m_evesdropString.size()+1];
std::copy(m_evesdropString.begin(),m_evesdropString.end(),charbuf);
charbuf[m_evesdropString.size()]='\0';
int iResult=send(m_socketClient,charbuf,strlen(charbuf),0);
memset(charbuf,0x00,sizeof(charbuf));
}
CreateThread(NULL,0,receiveClientData,this,0,NULL);
return true;
}
}
catch(SocketExceptions& i_exceptionInConnection)
{
shutdown(m_socketClient,SD_BOTH);
closesocket(m_socketClient);
m_socketClient=INVALID_SOCKET;
this->exceptionOccurred(EST_EXCEPTIONINCONNECT);
return false;
}
return true;
}
so please can anyone tell me what is the problem.?

It is not a good idea to use CreateThread() directly from C++ code. You should rather use _beginthreadex() to initialize C++ runtime environment for you thread (TLS variables and other stuff).

Related

Thread does not do anything

I try to use a thread to tell the user the COM port for serial communication he entered was wrong. I have a thread class which tries to establish the connection and a function in my main, that should tell the user.
The compiler does not complain, but my program never enters the function. Maybe anyone can spot the mistake I made.
main.cpp:
WindowsDgpsGUIFrame::WindowsDgpsGUIFrame(wxWindow* parent,wxWindowID id)
{
...
Bind(wxEVT_THREAD, &WindowsDgpsGUIFrame::onConnectionFailed, this, wxID_EXIT);
...
}
void WindowsDgpsGUIFrame::OnButtonStartClick(wxCommandEvent& event)
{
NavigationThread* navigationThread = new NavigationThread(this, m_usedVariables);
m_navigationThread = navigationThread;
wxThreadError err = m_navigationThread->Create();
if(err != wxTHREAD_NO_ERROR)
{
StaticStatusText->Enable();
StaticStatusText->SetLabel("Could not create NavigationThread.");
}
else{
StaticStatusText->SetLabel("Thread created");
}
err = m_navigationThread->Run();
if(err != wxTHREAD_NO_ERROR)
{
StaticStatusText->SetLabel("Could not run thread.");
}
}
void WindowsDgpsGUIFrame::onConnectionFailed(wxThreadEvent& event)
{
StaticConnectionText->SetLabel(event.GetString());
}
thread.cpp:
wxThread::ExitCode NavigationThread::Entry()
{
Serial serial;
int resultGnss = serial.Open(m_gnssPort, STANDARD_BAUDRATE);
wxThreadEvent event(wxEVT_THREAD, wxID_RETRY);
if(resultGnss != 0)
{
event.SetString("Connection to GNSS box not possible. Try with another COM port.");
m_parent->GetEventHandler()->AddPendingEvent(event);
}
else{
event.SetString("Connection successful");
m_parent->GetEventHandler()->AddPendingEvent(event);
}
return 0;
}
The thread gets created and starts running, but even though the event is thrown in the thread the program never reaches onConnectionFailed().

Is __finally supposed to run after EXCEPTION_CONTINUE_SEARCH?

In the following code, the function foo calls itself recursively once. The inner call causes an access violation to be raised. The outer call catches the exception.
#include <windows.h>
#include <stdio.h>
void foo(int cont)
{
__try
{
__try
{
__try
{
if (!cont)
*(int *)0 = 0;
foo(cont - 1);
}
__finally
{
printf("inner finally %d\n", cont);
}
}
__except (!cont? EXCEPTION_CONTINUE_SEARCH: EXCEPTION_EXECUTE_HANDLER)
{
printf("except %d\n", cont);
}
}
__finally
{
printf("outer finally %d\n", cont);
}
}
int main()
{
__try
{
foo(1);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
printf("main\n");
}
return 0;
}
The expected output here should be
inner finally 0
outer finally 0
inner finally 1
except 1
outer finally 1
However, outer finally 0 is conspicuously missing from the real output. Is this a bug or is there some detail I'm overlooking?
For completeness, happens with VS2015, compiling for x64. Surprisingly it doesn't happen on x86, leading me to believe that it is really a bug.
exist and more simply example (we can remove inner try/finally block:
void foo(int cont)
{
__try
{
__try
{
if (!cont) *(int *)0 = 0;
foo(cont - 1);
}
__except (cont? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
printf("except %d\n", cont);
}
}
__finally
{
printf("finally %d\n", cont);
}
}
with output
except 1
finally 1
so finally 0 block not executed. but in not recursive case - no bug:
__try
{
foo(0);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
printf("except\n");
}
output:
finally 0
except
this is bug in next function
EXCEPTION_DISPOSITION
__C_specific_handler (
_In_ PEXCEPTION_RECORD ExceptionRecord,
_In_ PVOID EstablisherFrame,
_Inout_ PCONTEXT ContextRecord,
_Inout_ PDISPATCHER_CONTEXT DispatcherContext
);
old implementation of this function with bug here :
//
// try/except - exception filter (JumpTarget != 0).
// After the exception filter is called, the exception
// handler clause is executed by the call to unwind
// above. Having reached this point in the scan of the
// scope tables, any other termination handlers will
// be outside the scope of the try/except.
//
if (TargetPc == ScopeTable->ScopeRecord[Index].JumpTarget) { // bug
break;
}
if we have latest VC compiler/libraries installed, search for chandler.c (in my install in located at \VC\crt\src\amd64\chandler.c )
and in file can view now next code:
if (TargetPc == ScopeTable->ScopeRecord[Index].JumpTarget
// Terminate only when we are at the Target frame;
// otherwise, continue search for outer finally:
&& IS_TARGET_UNWIND(ExceptionRecord->ExceptionFlags)
) {
break;
}
so additional condition is added IS_TARGET_UNWIND(ExceptionRecord->ExceptionFlags) which fix this bug
__C_specific_handler implemented in different crt libraries (in some case with static link, in some case will be imported from vcruntime*.dll or msvcrt.dll (was forwarded to ntdll.dll)). also ntdll.dll export this function - however in latest win10 builds(14393) it still not fixed

libspotify: Access violation reading location 0x00000000. (Windows)

So, I try to get a specific playlist via the URI like this:
sp_link *link;
sp_playlist *playlist;
sp_playlist_callbacks playlist_callbacks = { 0 };
link = sp_link_create_from_string("spotify:user:spotify:playlist:2iY4BLINjMOGJX4qHCWNju");
playlist_callbacks.playlist_state_changed = playlist_state_changed;
WaitForSingleObject(lib_lock, INFINITE);
playlist = sp_playlist_create(session, link); // <- Program crashes here
sp_playlist_add_callbacks(playlist, &playlist_callbacks, NULL);
WaitForSingleObject(lib_event_call_finished, INFINITE);
ReleaseMutex(lib_lock);
The callback is the following:
void SP_CALLCONV playlist_state_changed(sp_playlist *playlist, void *user_data)
{
if (sp_playlist_is_loaded(playlist)) {
SetEvent(lib_event_call_finished);
}
}
lib_lock is a mutex (CreateMutex(NULL, FALSE, NULL);)
lib_event_call_finshed is an event (CreateEvent(NULL, FALSE, FALSE, NULL);)
One word about my program's architecture:
I have a thread executing the above commands, which is created in the main function. The main function then executes the main loop:
while (true) {
result = WaitForSingleObject(lib_event_notify, next_timeout);
if (result == WAIT_OBJECT_0 || result == WAIT_TIMEOUT) {
do {
sp_session_process_events(session, &next_timeout);
} while (next_timeout == 0);
} else {
ERR_MSG("WaitForSingleObject has failed");
}
}
lib_event_notify is another event, which is called when notify_main_thread is called.
When the marked line is executed I get following error from Visual Studio:
Unhandled exception at 0x100A5550 (libspotify.dll) in prog.exe:
0xC0000005: Access violation reading location 0x00000000.

Mutex can't acquire lock

I have a problem where one of my functions can't aquire the lock on one of the 2 mutexes I use.
I did a basic debug in VC++2010 , setting some breakpoints and it seems if anywhere the lock is acquired, it does get unlocked.
The code that uses mutexes is as follow:
#define SLEEP(x) { Sleep(x); }
#include<windows.h>
void Thread::BackgroundCalculator( void *unused ){
while( true ){
if(MUTEX_LOCK(&mutex_q, 5) == 1){
if(!QueueVector.empty()){
//cut
MUTEX_UNLOCK(&mutex_q);
//cut
while(MUTEX_LOCK(&mutex_p,90000) != 1){}
//cut
MUTEX_UNLOCK(&mutex_p);
}
}
SLEEP(25);
}
}
Then somwhere else:
PLUGIN_EXPORT void PLUGIN_CALL
ProcessTick(){
if(g_Ticked == g_TickMax){
if(MUTEX_LOCK(&mutex_p, 1) == 1){
if(!PassVector.empty()){
PassVector.pop();
}
MUTEX_UNLOCK(&mutex_p);
}
g_Ticked = -1;
}
g_Ticked += 1;
}
static cell AMX_NATIVE_CALL n_CalculatePath( AMX* amx, cell* params ){
if(MUTEX_LOCK(&mutex_q,1) == 1){
QueueVector.push_back(QuedData(params[1],params[2],params[3],amx));
MUTEX_UNLOCK(&mutex_q);
return 1;
}
return 0;
}
init:
PLUGIN_EXPORT bool PLUGIN_CALL Load( void **ppData ) {
MUTEX_INIT(&mutex_q);
MUTEX_INIT(&mutex_p);
START_THREAD( Thread::BackgroundCalculator, 0);
return true;
}
Some variables and functions:
int MUTEX_INIT(MUTEX *mutex){
*mutex = CreateMutex(0, FALSE, 0);
return (*mutex==0);
}
int MUTEX_LOCK(MUTEX *mutex, int Timex = -1){
if(WaitForSingleObject(*mutex, Timex) == WAIT_OBJECT_0){
return 1;
}
return 0;
}
int MUTEX_UNLOCK(MUTEX *mutex){
return ReleaseMutex(*mutex);
}
MUTEX mutex_q = NULL;
MUTEX mutex_p = NULL;
and defines:
# include <process.h>
# define OS_WINDOWS
# define MUTEX HANDLE
# include <Windows.h>
# define EXIT_THREAD() { _endthread(); }
# define START_THREAD(a, b) { _beginthread( a, 0, (void *)( b ) ); }
Thread header file:
#ifndef __THREAD_H
#define __THREAD_H
class Thread{
public:
Thread ( void );
~Thread ( void );
static void BackgroundCalculator ( void *unused );
};
#endif
Well I can't seem to find the issue.
After debugging I wanted to "force" aquiring the lock by this code (from the pawn abstract machine):
if (strcmp("/routeme", cmdtext, true) == 0){
new fromnode = NearestPlayerNode(playerid);
new start = GetTickCount();
while(CalculatePath(fromnode,14,playerid+100) == 0){
printf("0 %d",fromnode);
}
printf("1 %d",fromnode);
printf("Time: %d",GetTickCount()-start);
return 1;
}
but it keeps endless going on, CalculatePath calls static cell AMX_NATIVE_CALL n_CalculatePath( AMX* amx, cell* params )
That was a bit of surprise. Does anyone maybe see a mistake?
If you need the full source code it is available at:
http://gpb.googlecode.com/files/RouteConnector_174alpha.zip
Extra info:
PLUGIN_EXPORT bool PLUGIN_CALL Load
gets only executed at startup.
static cell AMX_NATIVE_CALLs
get only executed when called from a vitrual machine
ProcessTick()
gets executed every process tick of the application, after it has finished its own jobs it calls this one in the extensions.
For now I only tested the code on windows, but it does compile fine on linux.
Edit: removed linux code to shorten post.
From what I see your first snippet unlocks mutex based on some condition only, i.e. in pseudocode it is like:
mutex.lock ():
if some_unrelated_thing:
mutex.unlock ()
As I understand your code, this way the first snippet can in principle lock and then never unlock.
Another potential problem is that your code is ultimately exception-unsafe. Are you really able to guarantee that no exceptions happen between lock/unlock operations? Because if any uncaught exception is ever thrown, you get into a deadlock like described. I'd suggest using some sort of RAII here.
EDIT:
Untested RAII way of performing lock/unlock:
struct Lock
{
MUTEX& mutex;
bool locked;
Lock (MUTEX& mutex)
: mutex (mutex),
locked (false)
{ }
~Lock ()
{ release (); }
bool acquire (int timeout = -1)
{
if (!locked && WaitForSingleObject (mutex, timeout) == WAIT_OBJECT_0)
locked = true;
return locked;
}
int release ()
{
if (locked)
locked = ReleaseMutex (mutex);
return !locked;
}
};
Usage could be like this:
{
Lock q (mutex_q);
if (q.acquire (5)) {
if (!QueueVector.empty ()) {
q.release ();
...
}
}
}
Note that this way ~Lock always releases the mutex, whether you did that explicitly or not, whether the scope block exited normally or due to an uncaught exception.
I'm not sure if this is intended behavior, but in this code:
void Thread::BackgroundCalculator( void *unused ){
while( true ){
if(MUTEX_LOCK(&mutex_q, 5) == 1){
if(!QueueVector.empty()){
//cut
MUTEX_UNLOCK(&mutex_q);
//cut
while(MUTEX_LOCK(&mutex_p,90000) != 1){}
//cut
MUTEX_UNLOCK(&mutex_p);
}
}
SLEEP(25);
}
if the QueueVector.empty is true you are never unlocking mutex_q.

exception while thread is throwing error in scoket c++ windows

i am creating client sever application in windows using socket and i want to throw exception at run time from thread if any problem occur but i am getting error for throw statement.
//create thread in cpp file
CreateThread(NULL,0,startServer,this,0,NULL);
//thread in header file
static unsigned long __stdcall startServer(void *i_SocketTransportServer)
{
((SocketTransportServer*)i_SocketTransportServer)->StartServerThread(((SocketTransportServer *)i_SocketTransportServer)->m_socketServer);
return 0;
}
//and StartServerThread is function called by thread
// SocketTransportServer is inner class of RMLThinTransport
void RMLThinTransport::SocketTransportServer::StartServerThread(SOCKET i_socketServer)
{
m_socketAccept=NULL;
while(true)
{
Sleep(20);
if(m_canAcceptMore)
{
m_canAcceptMore=false;
if(!m_isRunning)
{
break;
}
try
{
m_socketAccept=accept(m_socketServer,NULL,NULL);
if(m_socketAccept==INVALID_SOCKET)
{
int lastError=WSAGetLastError();
closesocket(m_socketAccept);
SocketExceptions
exceptionInAcceptAtServer;
exceptionInAcceptAtServer.detectErrorAccept(&lastError);
throw exceptionInAcceptAtServer;
}
else
{
//_LOG("Client connected",EventTypeInfo) ;
OutputDebugStringW(L"client connected.....");
/* If client connected then setClinetCout value 1 */
setClientCount(1);
m_ClientSockets.push_back(m_socketAccept);
CreateThread(NULL,0,receiveDataAtServer,this,0,NULL);
}
}
catch(SocketExceptions& i_exceptionInAcceptAtServer)
{
/*OutputDebugStringW(L"Can't accept client In Exception. ."); */
throw i_exceptionInAcceptAtServer;//getting runtime error from here
}
}
}
}
now i want to throw error when server close but i am getting run time error. so is there any way so i can get error in my main function.sorry but i am new in c++ so please help me. and error is
The code that throws the exception is not the problem; it's the lack of any code to catch the exception that's the problem. The application is terminating because nothing is catching the exception you're throwing; you must ensure that something is going to catch it. Your startServer method -- the thread procedure -- must catch the exception, and cleanly exit the thread.