Synchronize threads in C++ - c++

I have three threads - Thread1 prints "Good", Thread2 prints "Morning" and Thread3 prints "All". How do I use these threads to keep printing “Good Morning All” on the screen continuously?

For one, you are simply wasting resources.
However, assuming that you really need this to accomplish something more important than just printing words, here is a suggestion:
create 3 mutexes (pthread_mutex)
pthread_mutex_t m_Good, m_Morning, m_all;
pthread_mutex_init(&m_Good, NULL);
pthread_mutex_init(&m_Morning, NULL);
pthread_mutex_init(&m_All, NULL);
Lock last two mutexes
pthread_mutex_lock(&m_Morning);
pthread_mutex_lock(&m_All);
In first thread prints its message then unlock second mutex.
while(true){
if(pthread_mutex_lock(&m_Good)==0){
printf("GOOD ");
pthread_mutex_unlock(&m_Morning);
pthread_mutex_lock(&m_Good);
}
}
second thread prints message, locks its mutex and unlock third
third thread prints its message, unlock first mutex and locks third mutex

Here's a simple lock-free implementation for forcing sequential execution of threads. It uses an atomic state variable that can represent four possible states:
working = one of the threads is working
ready_for_task1 = it is task1's turn to start working
ready_for_task2 = it is task2's turn to start working
ready_for_task3 = it is task3's turn to start working
The general idea is to cycle through these states:
ready_for_task1 ->
working ->
ready_for_task2 ->
working ->
ready_for_task3 ->
working ->
ready_for_task1 ->
...
First part, define the states, declare the global atomic state, and define a guard class that performs the state transitions. The guard constructor of the guard will "busy" wait by atomically checking for its ready state and switching the state to working. The guard destructor will set the state to the next task's ready state.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <atomic>
enum State { ready_for_task1, ready_for_task2, ready_for_task3, working };
static std::atomic< State > state_;
class TransitionGuard {
public:
TransitionGuard(State start, State finish) : finish_(finish) {
State expecting = start;
while( !state_.compare_exchange_weak( expecting, working ) ) {
expecting = start;
asm("pause");
}
}
~TransitionGuard() {
state_.store( finish_ );
}
private:
const State finish_;
};
Then each thread runs their own loop, printing their word under their respective transition guard.
void * task1( void * data )
{
while( true ) {
TransitionGuard guard( ready_for_task1, ready_for_task2 );
printf( "Good" );
}
}
void * task2( void * data)
{
while( true ) {
TransitionGuard guard( ready_for_task2, ready_for_task3 );
printf( " Morning" );
}
return NULL;
}
void * task3( void * data)
{
while( true ) {
TransitionGuard guard( ready_for_task3, ready_for_task1 );
printf( " All\n" );
}
return NULL;
}
And finally, you'll want to initialize the state before creating the threads.
int main( int argc, const char ** argv )
{
state_ = ready_for_task1;
pthread_t thread1, thread2, thread3;
if( pthread_create( &thread1, NULL, task1, NULL ) )
{
fprintf( stderr, "thread1 failed to start\n" );
exit(EXIT_FAILURE);
}
if( pthread_create( &thread2, NULL, task2, NULL ) )
{
fprintf( stderr, "thread2 failed to start\n" );
exit(EXIT_FAILURE);
}
if( pthread_create( &thread3, NULL, task3, NULL ) )
{
fprintf( stderr, "thread3 failed to start\n" );
exit(EXIT_FAILURE);
}
pthread_join( thread1, NULL );
pthread_join( thread2, NULL );
pthread_join( thread3, NULL );
fprintf( stderr, "threads joined. exiting.\n" );
exit(EXIT_SUCCESS);
}

Related

Pthread: wake a thread from 4 threads

I have a problem with waking a thread in C++. I have 4 running threads. I want to wake my sleeping thread when the 4 running threads are completed. I did it with condition wait operation but it doesn't look good. How can I do this process in a better quality way?
4 tasks are triggered by broadcast and starts working on different cores at the same time. At the end of each task, it sets the flag of its own taskID to 1 and sends a signal to the sleeping task. The task in sleep state wakes up every time it receives a signal and checks the flag of each task. If the 4 task flag is 1, it continues and does its own work.
void *thread_sleep( void *arg )
{
pthread_mutex_lock(&mutex_sleep);
while(flag_task[0] == 0 || flag_task[1] == 0 || flag_task[2] == 0 || flag_task[3] == 0)
pthread_cond_wait(&cond_sleep, &mutex_sleep);
/*
.
.
.
.
*/
flag_task[0] = 0;
flag_task[1] = 0;
flag_task[2] = 0;
flag_task[3] = 0;
pthread_mutex_unlock(&mutex_sleep);
}
void *thread( void *arg)
{
int taskID = *(char *)arg - '0';
while(1)
{
pthread_mutex_lock(&mutex[taskID]);
pthread_cond_wait(&cond, &mutex[taskID]);
/*
.
.
.
.
*/
pthread_mutex_unlock(&mutex[taskID]);
flag_task[taskID] = 1;
pthread_cond_signal(&cond_sleep);
}
}
int main()
{
pthread_create( &pthread1, NULL, thread, (void *)"0" );
pthread_create( &pthread2, NULL, thread, (void *)"1" );
pthread_create( &pthread3, NULL, thread, (void *)"2" );
pthread_create( &pthread4, NULL, thread, (void *)"3" );
pthread_create( &pthread5, NULL, thread_sleep, (void *)"4" );
pthread_cond_broadcast(&cond);
}
I solved using barrier. Thank you #Quimby.
void *thread_sleep( void *arg )
{
pthread_mutex_lock(&mutex_sleep);
pthread_cond_wait(&cond_sleep, &mutex_sleep);
/*
.
.
.
.
*/
pthread_mutex_unlock(&mutex_sleep);
}
void *thread( void *arg)
{
int taskID = *(char *)arg - '0';
while(1)
{
pthread_mutex_lock(&mutex[taskID]);
pthread_cond_wait(&cond, &mutex[taskID]);
/*
.
.
.
.
*/
pthread_mutex_unlock(&mutex[taskID]);
pthread_barrier_wait(&barrier);
pthread_cond_signal(&cond_sleep);
}
}
int main()
{
pthread_barrier_init(&barrier, NULL, 4);
pthread_create( &pthread1, NULL, thread, (void *)"0" );
pthread_create( &pthread2, NULL, thread, (void *)"1" );
pthread_create( &pthread3, NULL, thread, (void *)"2" );
pthread_create( &pthread4, NULL, thread, (void *)"3" );
pthread_create( &pthread5, NULL, thread_sleep, (void *)"4" );
sleep(1);
pthread_cond_broadcast(&cond);
}

Windows SleepEx() doesn't resume when queueing an APC

I have the problem that a thread that was sent to sleep using SleepEx(INFINITE, true) does not reliably continue when an APC is queued.
The application scenario is that software A must notice when software B has installed a certain Windows service.
For this, I create a new thread, register a callback function via NotifyServiceStatusChange(), and put the thread to sleep via SleepEx(INFINITE, true).
If, during the runtime of software A, the specified service is installed, the callback function is called, the thread is continued, and finishes its run() method. Everything works fine.
But, if software A terminates without the callback function being called, I still want the thread to terminate properly.
The Microsoft documentation states this about the SleepEx function:
Execution resumes when one of the following occurs:
An I/O completion callback function is called.
An asynchronous procedure call (APC) is queued to the thread.
The time-out interval elapses.
Therefore, I queue an APC to my thread using QueueUserAPC(). This works fine, my function stopSleeping() is called and executed: A breakpoint can be reached and debug output can be made inside this function.
Unfortunately, contrary to my expectation, my own APC does not cause the thread to resume running, as the call of the function callback() does.
The question is, why not?
My thread is a class derived from QThread and the stopThread() method is triggered by a SIGNAL/SLOT connection from the main thread.
// **********************************************
void CCheckForService::run()
{
SC_HANDLE SCHandle = ::OpenSCManager( 0
, SERVICES_ACTIVE_DATABASE
, SC_MANAGER_ENUMERATE_SERVICE
);
if ( 0 != SCHandle )
{
meStatus = Status::BEFORE_NOTIFY_SVC_CHANGE;
SERVICE_STATUS_PROCESS ssp;
char text[] = "MyServiceToLookFor";
wchar_t wtext[ 20 ];
mbstowcs( wtext, text, strlen( text ) + 1 );
LPWSTR lpWText = wtext;
SERVICE_NOTIFY serviceNotify = { SERVICE_NOTIFY_STATUS_CHANGE
, &CCheckForIIoT::callback
, nullptr
, 0
, ssp
, 0
, lpWText
};
// Callback function is to be invoked if "MyServiceToLookFor" has been installed
const DWORD result = ::NotifyServiceStatusChange( SCHandle
, SERVICE_NOTIFY_CREATED
, &serviceNotify
);
if ( ERROR_SUCCESS == result )
{
meStatus = Status::WAITING_FOR_CALLBACK;
::SleepEx( INFINITE, true ); // Wait for the callback function
}
LocalFree( lpWText );
}
::CloseServiceHandle( SCHandle );
if ( Status::CANCELLED != meStatus )
{
// inform main thread
emit sendReady( meStatus );
}
}
// **********************************************
// [static]
void CCheckForService::stopSleeping( ULONG_PTR in )
{
Q_UNUSED( in )
meStatus = Status::CANCELLED;
}
// **********************************************
// [static]
void CCheckForService::callback( void* apParam )
{
auto lpServiceNotify = static_cast< SERVICE_NOTIFY* >( apParam );
// the service is now installed; now wait until it runs
{
QtServiceController lBrokerService( "MyServiceToLookFor" );
QTime WaitTime;
WaitTime.start();
while ( !lBrokerService.isRunning() )
{
msleep( 1000 );
// Timeout check
if ( WaitTime.elapsed() > WAIT_FOR_SERVICE_RUN * 1000 )
{
break;
}
}
}
meStatus = Status::OK;
}
// **********************************************
// [SLOT]
void CCheckForService::stopThread( void )
{
HANDLE ThreadHandle( ::OpenThread( THREAD_ALL_ACCESS
, true
, ::GetCurrentThreadId()
)
);
DWORD d = ::QueueUserAPC( &CCheckForIIoT::stopSleeping
, ThreadHandle
, NULL
);
::CloseHandle( ThreadHandle );
}
I'm not 100% sure on this, given that you didn't provide a runnable example it's hard to verify.
My guess is that you're scheduling the APC on the main thread, instead of the CCheckForService thread.
If CCheckForService::stopThread is called from a signal/slot on the main thread, then it'll execute on the main thread.
So ::GetCurrentThreadId() will return the thread id of the main thread, and you subsequently end up with calling QueueUserAPC() with a thread handle for the main thread, so the APC will execute on the main thread.
So the CCheckForService will remain sleeping, because it never received an APC.
You can verify this by comparing QApplication::instance()->thread() with QThread::currentThread() inside your CCheckForService::stopSleeping method - if they're equal you scheduled the APC on the main thread instead of the worker.
There's unfortunately no officially supported way in QT to get the thread id / thread handle of a QThread, apart from calling QThread::currentThreadId().
So you'd have to store the thread id in your CCheckForService class, so you can later get the appropriate thread handle, e.g.:
// TODO: Add to CCheckForService declaration
// private: DWORD runningThreadId;
// TODO: initialize runningThreadId in constructor to 0
// 0 is guaranteed to never be a valid thread id
void CCheckForService::run() {
runningThreadId = ::GetCurrentThreadId();
/** ... Rest of original run() ... **/
}
void CCheckForService::stopThread( void )
{
HANDLE ThreadHandle( ::OpenThread( THREAD_ALL_ACCESS
, true
, runningThreadId /* <------ */
)
);
DWORD d = ::QueueUserAPC( &CCheckForIIoT::stopSleeping
, ThreadHandle
, NULL
);
::CloseHandle( ThreadHandle );
}
There's still a small race condition left in this example though - if you call stopThread() before the thread has started up & set the runningThreadId. In that case OpenThread() will fail and return NULL, so queuing the APC will fail.

Auto Thread resume c++

i build Simple Anticheat module for a game and i need protect the Thread's from a Suspend (Like Suspend Thread from Processhacker).
Is there any way to automatically resume the thread if is suspended?
Here is my module code:
#include "stdafx.h"
#include "Start.h"
void Msg_Sf_Br(){
MessageBoxA(NULL,"SpeedHack - Detect", load.Nome_das_Janelas, MB_SERVICE_NOTIFICATION | MB_ICONWARNING);
ExitProcess(0);
}
void Msg_Sf_En(){
MessageBoxA(NULL,"SpeedHack - Detect", load.Nome_das_Janelas, MB_SERVICE_NOTIFICATION | MB_ICONWARNING);
ExitProcess(0);
}
void Speed_perf()
{
if( *(unsigned long*)QueryPerformanceCounter != 2337669003 ){
if (load.Log_Txt_Hack == 1){
}
if (load.Message_Warning_En == 1){
ExitProcess(0);
}
if (load.Message_Warning_En == 2){
CreateThread(NULL,NULL,LPTHREAD_START_ROUTINE(Msg_Sf_Br),NULL,0,0);
Sleep(3000);
ExitProcess(0);
}
if (load.Message_Warning_En == 0){
ExitProcess(0);
}
else
ExitProcess(0);
}
}
void performance(){
if (load.Anti_Kill_Scans == 1)
{
again:
Speed_perf();
Sleep(load.Detecta_Speed_PerformanceT);
goto again;
}
else
{
again2:
Speed_perf();
Sleep(load.Detecta_Speed_PerformanceT);
goto again2;
}
}
void SPerformance(){
CreateThread(NULL,NULL,LPTHREAD_START_ROUTINE(performance),NULL,0,0);
}
Any idea?
With a little trick you can hide your thread from any debugger or tools like process hacker.
void func()
{
}
int main()
{
int(__stdcall* ZwCreateThreadEx)(HANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, HANDLE, PVOID, PVOID, ULONG, ULONG_PTR, SIZE_T, SIZE_T, PVOID) = (decltype(ZwCreateThreadEx))GetProcAddress(GetModuleHandle("ntdll.dll"),"ZwCreateThreadEx");
HANDLE hThread=0;
ZwCreateThreadEx(&hThread,0x1FFFFF,0,GetCurrentProcess(),
(LPTHREAD_START_ROUTINE)func,0, 0x4/*hide flag*/,0,0x1000,0x10000,0);
return 0;
}
You can do it this way:
get list of process thread ids, using CreateToolhelp32Snapshot
go to first thread using methods: Thread32First.
for each found thread (you should check if belong to the given process):
then Open the thread using OpenThread in manner to retrieve handle to the thread from it thread id,
when you have the handle, you can suspend the thread using SuspendThread in manner to retrieve the previous suspension count,
then you can Resume the thread until it suspension count is 0. you must resume at least once in manner to cancel the suspension from the previous step.
if thread are not allowed to be suspended, you can use ResumeThread just to get the suspension count even if it was not suspended.
Close the thread handle using CloseHandle
iterate to next thread use Thread32Next.
In manner to be able to do the whole thing you must run as administrator.
Here is an example:
void TraverseProcessThreads(DWORD pid)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); //get list of all system thread
if( hSnapshot == INVALID_HANDLE_VALUE)
{
//print error and return;
return;
}
THREADENTRY32 threadEntry;
if( Thread32First( hSnapshot, &threadEntry) )
{
size_t threadsCounter = 0, suspendedThreadsCounter=0;
do{
if(te.th32OwnerProcessID == pid) //we get all threads in system, should filter the relevant pid.
{
threadsCounter ++; //found thread
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS,FALSE,te.th32ThreadID); //get handle to thread from its thread id
if(hThread == NULL) //
{
//print error and break. (will be permission error if not administrator)
break;
}
int suspensionCount = SuspendThread( hThread ) ;//will return previous suspension count. you can also use ResumeThread if there's no way it can be suspended.
if(suspensionCount > 0)
{
//thread was suspended
suspendedThreadsCounter ++;
}
//cancel our suspension...
suspensionCount = ResumeThread(hThread );
/*to resume suspended thread use ResumeThread until it return 1.
do{
suspensionCount = ResumeThread(hThread );
}while (suspensionCount > 1); //similar to Suspend Resume return previous Suspention count.
*/
}
CloseHandle(hThread);
}while(Thread32Next( hSnapshot, &threadEntry) );
//print results:
cout<<"process id"<<pid<<endl<<" has "<<threadsCounter <<" threads " <<endl
<<suspendedThreadsCounter <<" threads was suspended"<<endl;
}
else{
//print some error...
}
CloseHandle(hSnapshot);
}

Wait notify pthreads unix C++

I have n threads , each modifying an object O(k) where k can be 0 to n-1.
Now there is a listener thread l, that needs to get an alert when any of the thread,k, has modified its object O(k)
What is the fastest way to implement this situation ?
Use a Posix (or even better, std C++) condition variable, as one commentor already suggested. You can use the related mutex to protect a std::array of flags, one flag per worker thread. When a worker thread modifies its object, it acquires mutex and raises its flag. When the listener thread is notified, it will service the k:th object (corresponding to k:th flag in array) and lower the flag, then release mutex.
Be sure to read examples for condvars so you understand when mutex is automatically acquired/released.
In general, std C++ threading primitives are easier to use, since they use e.g. RAII for automatic unlocking of mutexes etc. Also portable to non-Posix environments. But here is a pthreads example from
http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
#define COUNT_DONE 10
#define COUNT_HALT1 3
#define COUNT_HALT2 6
main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, NULL, &functionCount1, NULL);
pthread_create( &thread2, NULL, &functionCount2, NULL);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Final count: %d\n",count);
exit(EXIT_SUCCESS);
}
// Write numbers 1-3 and 8-10 as permitted by functionCount2()
void *functionCount1()
{
for(;;)
{
// Lock mutex and then wait for signal to relase mutex
pthread_mutex_lock( &count_mutex );
// Wait while functionCount2() operates on count
// mutex unlocked if condition varialbe in functionCount2() signaled.
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionCount1: %d\n",count);
pthread_mutex_unlock( &count_mutex );
if(count >= COUNT_DONE) return(NULL);
}
}
// Write numbers 4-7
void *functionCount2()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
if( count < COUNT_HALT1 || count > COUNT_HALT2 )
{
// Condition of if statement has been met.
// Signal to free waiting thread by freeing the mutex.
// Note: functionCount1() is now permitted to modify "count".
pthread_cond_signal( &condition_var );
}
else
{
count++;
printf("Counter value functionCount2: %d\n",count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= COUNT_DONE) return(NULL);
}
}

Problem with ReleaseMutex

I'm writing an API and I'm facing problems with a Mutex.
The main thread, at some point, does:
void sendMessage (char* g_lpTxBuffer)
{
for ( int i = 0; ( i < 2) && ( FALSE == g_bAckRecvd) ; i++ )
{
sendToSerial( g_lpTxBuffer );
g_iRecvMessage = YES;
g_iState = WAITING_FOR_ACK;
Sleep(50);
}
WaitForSingleObject(g_hMutex, INFINITE);
and I have a child thread, who does:
DWORD WINAPI ThreadProc(void* lpv)
{
g_hMutex = OpenMutex( MUTEX_ALL_ACCESS, FALSE, "MUTEX_RECEIVE" );
while (TRUE)
{
g_bNAKflag = FALSE;
if ( YES == g_iRecvMessage )
{
WaitForSingleObject(g_hMutex, INFINITE);
receiveMessage();
}
if ( MESSAGE_READY == g_iState )
{
processMessage(); // interpret the message
if ( FALSE == g_bNAKflag )
{
g_iState = IDLE;
}
ReleaseMutex(g_hMutex);
}
} // while
return 0;
}
What I found is, if I place the ReleaseMutex() at the place pointed above, the main thread never comes back from the WaitForSingleObject() function. However, if I place it inside the
if ( YES == g_iRecvMessage )>
(which is not good because the receiveMessage is called several times, to receive byte per byte from the serial) it works, and the WaitForSingleObject runs fine..
I create the mutex with
g_hMutex = CreateMutex(NULL, FALSE, "MUTEX_RECEIVE");
and I checked, the ReleaseMutex() returns true
Any ideas?
Thanks..