I have a program in which we can monitor 2 objects at same time.
myThread = new thread (thred1, id);
vec.push_back (myThread);
In thred1 function,i use Boolean function to read the stored values from a different vector and it runs parallely like this:
element found 2 -- hj
HUMIDITY-1681692777 DISPLAYED IN RH
element found 1 -- hj
TEMPERATURE--1714636915 IN DEGREE CELSIUS
This keeps on running as that is what my program should do.
I have a case where I need to get ID from the user and stop that particular thread and the other should keep running till I stop it.Can someone help me with that?
void thred1 (int id)
{
bool err = false;
while (stopThread == false)
{
for (size_t i = 0; i < v.size (); i++)
{
if (id == v[i]->id)
{
cout << "element found " << v[i]->id << " -- " << v[i]->name << endl;
v[i]->Read ();
this_thread::sleep_for (chrono::seconds (4));
err = true;
break;
}
}
if (!err)
{
cout << "element not found" << endl;
break;
}
}
}
Suspension
1. Assuming you want to suspend the monitor thread but only temporarily (i.e making any changes) then you can just use a mutex. Lock it before accessing the shared vector and unlock it when you're done, ensuring that only one thread can access the data at a time.
2. You can actively suspend the thread using OS support such as SuspendThread and ResumeThread, in the case of Windows, when it's ready.
Termination
1. You could use an event for each monitor thread, name being linked to the ID would work. At each iteration of the monitor check for the termination event, ending the thread if it's active.
2. Pass some variable to each thread, store them in a map with the thread handle being the key, and similar to the previous option just check the value for each iteration.
3. Store all threads in a map with the handle as key, terminating it directly with OS support.
Honestly there are a ton of ways to do this, the best implementation depends on why exactly you want to stop the monitor thread. Any sort of synchronization object like a mutex should be fine if you're reading from one thread and writing from another. Otherwise, just storing all threads with the internal ID as key and the thread as the value should be fine for terminating monitor threads on demand.
Related
I am making a MT Ray-Tracer multithreading, and as the title says, its taking twice as much to execute as the single thread version. Obviously the purpose is to cut the render time by the half, however what I am doing now is just to send the ray-tracing method to run twice, one for each thread, basically executing the same rendering twice. Nonetheless, as threads can run in parallel, shall not there be a meaningful increase in execution time. But is about doubling.
This has to be related to my multithreading setup. I think its related to the fact I create them as joinable. So I am going to explain what I am doing and also put the related code to see if someone can confirm if that's the issue.
I create two threads and set them as joinable so. Create a RayTracer that allocates enough memory to store the image pixels (this is done in the constructor). Run a two iterations loop for sending relevant info for each thread, like the thread id and the adress of the Raytracer instance.
Then pthread_create calls run_thread, whose purpose is to call the ray_tracer:draw method where the work is done. On the draw method, I have a
pthread_exit (NULL);
as the last thing on it (the only MT thing on it). Then do another loop to join the threads. Finally I star to write the file in a small loop. Finally close the file and delete the pointers related to the array used to store the image in the draw method.
I may not need to use to join now that I am not doing a "real" multithreading ray-tracer, just rendering it twice, but as soon as I start alternate between the image pixels (ie, thread0 -> renders pixel0 - thread0 -> stores pixel0, thread1 -> renders pixel1 - thread1 -> stores pixel1, thread0 -> renders pixel2 - thread0 -> stores pixel2, , thread1 -> renders pixel3 - thread1 -> stores pixel3,etc...) I think I will need it so to be able to write the pixels in correct order on a file.
Is that correct? Do I really need to use join here with my method (or with any other?). If I do, how can I send the threads to run concurrently, not waiting for the other to complete? Is the problem totally unrelated to join?
pthread_t threads [2];
thread_data td_array [2];
pthread_attr_t attr;
void *status;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
TGAManager tgaManager ("z.tga",true);
if (tgaManager.isFileOpen()) {
tgaManager.writeHeadersData (image);
RayTracer rt (image.getHeight() * image.getWidth());
int rc;
for (int i=0; i<2; i++) {
//cout << "main() : creating thread, " << i << endl;
td_array[i].thread_id=i;
td_array[i].rt_ptr = &rt;
td_array[i].img_ptr = ℑ
td_array[i].scene_ptr = &scene;
//cout << "td_array.thread_index: " << td_array[i].thread_id << endl;
rc = pthread_create (&threads[i], NULL, RayTracer::run_thread, &td_array[i]);
}
if (rc) {
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
pthread_attr_destroy(&attr);
for (int i=0; i<2; i++ ) {
rc = pthread_join(threads[i], &status);
if (rc) {
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
}
//tgaManager.writeImage (rt,image.getSize());
for (int i=0; i<image.getWidth() * image.getHeight(); i++) {
cout << i << endl;
tgaManager.file_writer.put (rt.b[i]);
tgaManager.file_writer.put (rt.c[i]);
tgaManager.file_writer.put (rt.d[i]);
}
tgaManager.closeFile(1);
rt.deleteImgPtr ();
}
You do want to join() the threads, because if you don't, you have several problems:
How do you know when the threads have finished executing? You don't want to start writing out the resulting image only to find that it wasn't fully calculated at the moment you wrote it out.
How do you know when it is safe to tear down any data structures that the threads might be accessing? For example, your RayTracer object is on the stack, and (AFAICT) your threads are writing into its pixel-array. If your main function returns before the the threads have exited, there is a very good chance that the threads will sometimes end up writing into a RayTracer object that no longer exists, which will corrupt the stack by overwriting whatever other objects might exist (by happenstance) at those same locations after your function returned.
So you definitely need to join() your threads; you don't need to explicitly declare them as PTHREAD_CREATE_JOINABLE, though, since that attribute is already set by default anyway.
Joining the threads should not cause the threads to slow down, as long as both threads are created and running before you call join() on any of them (which appears to be the case in your posted code).
As for why you are seeing a slowdown with two threads, that's hard to say since a slowdown could be coming from a number of places. Some possibilities:
Something in your ray-tracing code is locking a mutex, such that for much of the ray-tracing run, only one of the two threads is allowed to execute at a time anyway.
Both threads are writing to the same memory locations at around the same time, and that is causing cache-contention which slows down the execution of both threads.
My suggestion would be to set your threads so that thread #1 renders only the top half of the image, and thread #2 renders only the bottom half of the image; that way when they write their output they will be writing to different sections of memory.
If that doesn't help, you might temporarily replace the rendering code with something simpler (e.g. a "renderer" that just sets pixels to random values) to see if you can see a speedup with that. If so, then there might be something in your RayTracer's implementation that isn't multithreading-friendly.
In QT, from main(GUI) thread I am creating a worker thread to perform a certain operation which accesses a resource shared by both threads. On certain action in GUI, main thread has to manipulate the resource. I tried using QMutex to lock that particular resource. This resource is continuously used by the worker thread, How to notify main thread on this?
Tried using QWaitCondition but it was crashing the application.
Is there any other option to notify and achieve synchronisation between threads?
Attached the code snippet.
void WorkerThread::IncrementCounter()
{
qDebug() << "In Worker Thread IncrementCounter function" << endl;
while(stop == false)
{
mutex.lock();
for(int i = 0; i < 100; i++)
{
for(int j = 0; j < 100; j++)
{
counter++;
}
}
qDebug() << counter;
mutex.unlock();
}
qDebug() << "In Worker Thread Aborting " << endl;
}
//Manipulating the counter value by main thread.
void WorkerThread::setCounter(int value)
{
waitCondition.wait(&mutex);
counter = value;
waitCondition.notify_one();
}
You are using the wait condition completely wrong.
I urge you to read up on mutexes and conditions, and maybe look at some examples.
wait() will block execution until either notify_one() or notify_all() is called somewhere. Which of course cannot happen in your code.
You cannot wait() a condition on one line and then expect the next two lines to ever be called if they contain the only wake up calls.
What you want is to wait() in one thread and notify_XXX() in another.
You could use shared memory from within the same process. Each thread could lock it before writing it, like this:
QSharedMemory *shared=new QSharedMemory("Test Shared Memory");
if(shared->create(1,QSharedMemory::ReadWrite))
{
shared->lock();
// Copy some data to it
char *to = (char*)shared->data();
const char *from = &dataBuffer;
memcpy(to, from, dataSize);
shared->unlock();
}
You should also lock it for reading. If strings are wanted, reading strings can be easier that writing them, if they are zero terminated. You'll want to convert .toLatin1() to get a zero-terminated string which you can get the size of a string. You might get a lock that multiple threads can read from, with shared->attach(); but that's more for reading the shared memory of a different process..
You might just use this instead of muteces. I think if you try to lock it, and something else already has it locked, it will just block until the other process unlocks it.
Suppose there are 5 threads waiting for a semaphore
CreateSemaphore(sem_bridgempty,0,1,INFINITE);
WaitForSingleObject(sem_bridgempty, INFINITE);
Now when sem_bridgeempty is signalled, one of the 5 threads will wake up and rest will again wait for sem_bridgeempty to be signalled.Am i right here?
I am implementing one lane bridge problem where there can be vehicles moving from one direction only at a time.Also the capacity of the bridge is fixed at 5.What i have done so far is
unsigned WINAPI enter(void *param)
{
int direction = *((int *)param);
while (1)
{
WaitForSingleObject(sem_bridgecount, INFINITE);
WaitForSingleObject(mut_mutex, INFINITE);
if (curr_direction == -1 || direction == curr_direction)
{
curr_direction = direction;
cars_count++;
std::cout << "Car with direction " << direction << " entered " << GetCurrentThreadId() << std::endl;
ReleaseMutex(mut_mutex);
break;
}
else
{
ReleaseMutex(mut_mutex);
WaitForSingleObject(sem_bridgempty, INFINITE);
}
}
Sleep(5000);
exit1(NULL);
return 0;
}
unsigned WINAPI exit1(void *param)
{
WaitForSingleObject(mut_mutex, INFINITE);
cars_count--;
std::cout << "A Car exited " << GetCurrentThreadId() << std::endl;
ReleaseSemaphore(sem_bridgecount, 1, NULL);
if (cars_count == 0)
{
curr_direction = -1;
std::cout << "Bridge is empty " << GetCurrentThreadId() << std::endl;
ReleaseSemaphore(sem_bridgempty, 1, NULL);
}
ReleaseMutex(mut_mutex);
return 0;
}
int main()
{
sem_bridgecount = CreateSemaphore(NULL, 5, 5, NULL);
sem_bridgempty = CreateSemaphore(NULL, 0, 1, NULL);
mut_mutex = CreateMutex(NULL, false, NULL);
//create threads here
}
Consider the below portion
else
{
ReleaseMutex(mut_mutex);
WaitForSingleObject(sem_bridgempty, INFINITE);
A car is going in direction 1.Now there are three enter requests with direction 2.All 3 will be blocked at WaitForSingleObject(sem_bridgempty, INFINITE);.Now when the bridge goes empty.One of the three will be picked up.The one picked up will again make bridge non empty.Then the other two will still wait for the bridge to go empty even though the direction is same.
So even though there is direction=2 car on the bridge, other cars with the same direction are still waiting for the sem_bridgempty.
I even thought of using sem_bridgempty as an event instead of semaphore(setevent() in exit1() when cars_count=0 and resetevent() in enter() when first car enters).But still all threads don't wake up.
The cleanest option would be to use a critical section and a condition variable.
The ENTER algorithm would look like this:
Claim the critical section.
Call SleepConditionVariableCS in a loop, as shown in Using Condition Variables, until either:
The traffic is going in the right direction and the bridge has capacity left, or
The bridge is empty.
Update the state to represent your car entering the bridge.
Release the critical section.
The EXIT algorithm would look like this:
Claim the critical section.
Update the state to represent your car leaving the bridge.
Release the critical section.
Call WakeConditionVariable.
The condition variable could be an integer whose magnitude represents the number of cars on the bridge and whose sign represents the direction of travel.
If you wanted to avoid condition variables, the simplest solution I could come up with requires one critical section and three auto-reset events: one for each direction of travel, plus one to indicate that the bridge is empty. You will also need a variable representing the number of cars on the bridge.
The ENTER algorithm would look like this:
Using WaitForMultipleObjects, claim the event corresponding to your direction of travel or the event corresponding to the bridge being empty, whichever is available first.
Enter the critical section.
Increment the count to represent your car entering the bridge.
If the count is not at capacity, set the event representing your direction of travel.
Leave the critical section.
The EXIT algorithm would look like this:
Enter the critical section.
Decrement the count to represent your car leaving the bridge.
If the count is zero, set the event indicating that the bridge is empty.
If the count is nonzero, set the event corresponding to your direction of travel.
Release the critical section.
need create objects which most corresponded to task. in current task - we have 2 queues - on both direction. both this queue is FIFO by sense. and we need have ability wake exactly count of entries in queue - not only one or all. the windows semaphore is exactly correspond to this. this is FIFO queue and by call ReleaseSemaphore we can exactly set amount of threads (entries) to wake - this is second parameter of api lReleaseCount. in case event or ConditionVariable we can only wake single or all waiters.
your mistake not in that you select semaphore - this is the best choice for this task. you mistake that you select it for wrong essences - sem_bridgecount, sem_bridgempty - which is not queue by sence at all. you ned have 2 semaphores for 2 directions - HANDLE _hSemaphore[2]; - one semaphore per direction - create it as _hSemaphore[0] = CreateSemaphore(0, 0, MAXLONG, 0) - initial count is 0 (!) and maximum count is unlimited (but can select any value >= 5). when car try enter to bridge in direction and can not, because now another direction is active or no free space on bridge - it must wait on semaphore (in FIFO queue) _hSemaphore[direction]. and when car exit from bridge - he need check current situation on bridge and wake one or another direction on some exactly cars count (n) (not all or single) - so call ReleaseSemaphore(_hSemaphore[direction], n, 0);
in general:
void enter(int direction)
{
EnterCriticalSection(..);
BOOL IsNeedWait = fn(direction);
LeaveCriticalSection(..);
if (IsNeedWait) WaitForSingleObject(_hSemaphore[direction], INFINITE)
}
and
void exit(int direction)
{
EnterCriticalSection(..);
direction = calc_new(direction);
if (int WakeCount = calc_wake_count(direction))
{
ReleaseSemaphore(_hSemaphore[direction], WakeCount, 0);
}
LeaveCriticalSection(..);
}
note that in every enter - car only once enter to CriticalSection and after wait on _hSemaphore[direction] it just enter to bridge without again enter to cs and check conditions. this is because we can calculate exactly cars count (not single or all) and direction in exit - and wake only cars which and must enter to bridge, this will be impossible if use events or conditional variables
despite solution with conditional variables and CS is possible, i think it not best because:
thread after wait in SleepConditionVariableCS - again enter to cs which is absolute not need
we need or wake only single car by WakeConditionVariable when really can multiple cars enter to bridge, or wake all by WakeAllConditionVariable
but in this case several threads in concurrent again try enter to the same cs and only one will be winner, another will be wait here
count of waiting threads can be more than maximum place on bridge (5 in your case) - and some threads will be need begin wait again in loop.
all this can be avoid if correct use semaphore
full working implementation here
This is my sender thread once after it is called for first time its finish its execution. I Couldn't be able to resume this sender thread. Is There any mechanism in C++ to resume threads.
void ClientSocket::sender()
{
char buf[1024];
//readBuffer = m_ptrsendStream->Read_Adt(filePath);
//readStream();
//cout << readBuffer.str()<<endl;
cout << "write stream to send through socket\n" << endl;
cin >> buf;
if (isConnected == 0)
{
//send(clientSock, readBuffer.str().c_str(), strlen((char *)readBuffer.str().c_str()), 0);
send(clientSock, buf, strlen(buf), 0);
cout << "sending stream :\n"<<endl << buf << endl;
}
}
//this is where my thread creation happens and join() happens.
int main(int argc, char *argv[])
{
ClientSocket objSocket(argv[1]);
sender_thread = make_shared<thread>([&objSocket]() {
objSocket.sender();
});
try
{
if (sender_thread->joinable())
sender_thread->join();
}
No, once your thread has joined it's done and you need to create a new one.
If you have this pattern where you are constantly creating new threads it might be worthwhile to think about using a threadpool to avoid the overhead of constantly spawning new threads.
In addition, if this is related to networking it's probably best to avoid using threads and instead use something asynchronous like boost::asio.
Terminated threads cannot be resumed (this is not a C++ limitation, but a general limitation; when speaking about resuming thread, it is usually about resuming after previously suspending it).
After join() has returned, corresponding thread is already terminated; it has no state (except maybe for zobmie stuff and return code, but this is of no use for your purposes), and there is nothing to resume
However, it is possible to run your sender() function in another thread, just create another instance of your thread.
EDIT: I concur with #inf on using asio instead of threads whenever possible.
You want resume thread which is completed , normally thread resume used continue from suspended threads . Instead of resuming the thread ,stop come of thread un till it finish all actions , make use of while or wait in thread .
in my program there's a part of code that waits to be waken up from other part of code:
Here's the part that goes to sleep:
void flush2device(int task_id) {
if (pthread_mutex_lock(&id2cvLock) != SUCCESS) {
cerr << "system error - exiting!!!\n";
exit(1);
}
map<int,pthread_cond_t*>::iterator it;
it = id2cv.find(task_id);
if(it == id2cv.end()){
if (pthread_mutex_unlock(&id2cvLock) != SUCCESS) {
cerr << "system error\n UNLOCKING MUTEX flush2device\n";
exit(1);
}
return;
}
cout << "Waiting for CV signal" <<endl;
if(pthread_cond_wait(it->second, &id2cvLock)!=SUCCESS){
cerr << "system error\n COND_WAIT flush2device - exiting!!!\n";
exit(1);
}
cout << "should be right after " << task_id << " signal" << endl;
if (pthread_mutex_unlock(&id2cvLock) != SUCCESS) {
cerr << "system error\n UNLOCKING MUTEX flush2device -exiting!!!\n";
exit(1);
}
}
In another part of code, there's the waking up part (signaling):
//id2cv is a map <int, pthread_cond_t*> variable. - the value is a pointer to the cv on
//which we call with the broadcast method.
if(pthread_mutex_lock(&id2cvLock)!=SUCCESS){
cerr <<"system error\n";
exit(1);
}
id2cv.erase(nextBuf->_taskID);
cout << "In Thread b4 signal, i'm tID " <<nextBuf->_taskID << endl;
if (pthread_cond_broadcast(nextBuf->cv) != 0) {
cerr << "system error SIGNAL_CV doThreads\n";
exit(1);
}
cout << "In doThread, after erasing id2cv " << endl;
if(pthread_mutex_unlock(&id2cvLock)!=SUCCESS){
cerr <<"system error\n;
exit(1);
}
Most of the runnings work just fine, but once in a while the program just stop "reacting" - the first method (above) just doesn't pass the cond_wait part - it seems like no one really send her the signal on time (or from some other reason) - while the other method (which the last part of code is a part of it) keeps running.
Where do i go wrong in the logic of mutexes and signaling? I've already checked that the pthread_cond_t variable is still "alive" before the calling to the cond_wait and the cond_broadcast method, and nothing in that area seems to be the fault.
Despite it's name, pthread_cond_wait is an unconditional wait for a condition. You must not call pthread_cond_wait unless you have confirmed that there is something to wait for, and the thing it's waiting for must be protected by the associated mutex.
Condition variables are stateless and it is the application's responsibility to store the state of the thing being waited for, called a 'predicate'.
The canonical pattern is:
pthread_mutex_lock(&mutex);
while(!ready_for_me_to_do_something)
pthread_cond_wait(&condvar, &mutex);
do_stuff();
ready_for_me_to_do_something=false; // this may or may not be appropriate
pthread_mutex_unlock(&mutex);
and:
pthread_mutex_lock(&mutex);
ready_for_me_to_do_something=true;
pthread_cond_broadcast(&condvar);
pthread_mutex_unlock(&mutex);
Notice how this code maintains the state in the ready_for_me_to_do_something variable and the waiting thread waits in a loop until that variable is true. Notice how the mutex protects that shared variable, and it protects the condition variable (because that is also shared between the threads).
This is not the only correct way to use a condition variable, but it is very easy to run into trouble with any other use. You call pthread_cond_wait even if there is no reason to wait. If you wait for your sister to get home with the car before you use it, and she has already returned, you will be waiting a long time.
Your use of pthread_cond_wait() is not correct. If a condition variable is signalled while no processes are waiting, the signal has no effect. It's not saved for the next time a process waits. This means that correct use of pthread_cond_wait() looks like:
pthread_mutex_lock(&mutex);
/* ... */
while (!should_wake_up)
pthread_cond_wait(&cond, &mutex);
The should_wake_up condition might just be a simple test of a flag variable, or it might be something like a more complicated test for a buffer being empty or full, or something similar. The mutex must be locked to protect against concurrent modifications that might change the result of should_wake_up.
It is not clear what that test should be in your program - you might need to add a specific flag variable.
I don't think there's enough code in the "waking up" part, but my initial guess is that the pthread_cond_wait hasn't been entered at the time pthread_cond_broadcast is issued.
Another possibility is that pthread_cond_wait is in the middle of a spurious wakeup and misses the signal completely.
I'm pretty sure that most uses of condition variables also have an external predicate that must be checked after every wakeup to see if there is work to be done.