Have a pthread that sleeps while waiting on a condition variable. I use a boolean in the outer while loop to keep it running. The problem I seem to have is when I change this variable the thread does not die.
I took a look in instruments and if I start a thread , tell it to die, then start a new one my thread count is 2 not 1.
How can I properly destroy this thread when I want to?
int worktodo=0;
BOOL runthread=NO;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void *threadfunc(void *parm)
{
int rc;
while(runthread==YES)
{
rc=pthread_mutex_lock(&mutex);
while(!worktodo)
{
printf("thtread blocked\n");
rc=pthread_cond_wait(&cond, &mutex);
}
printf("thtread awake.... doing work\n");
// doing work
worktodo=0;
rc=pthread_mutex_unlock(&mutex);
}
// never reaches here!!
pthread_detach(NULL);
}
void makeThread()
{
pthread_attr_t attr;
int returnVal;
returnVal = pthread_attr_init(&attr);
assert(!returnVal);
runthread=YES;
returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
assert(!returnVal);
int threadError = pthread_create(&str->thread, &attr, &threadfunc, NULL);
returnVal = pthread_attr_destroy(&attr);
assert(!returnVal);
if (threadError != 0)
{
// Report an error.
}
}
void wakethread()
{
pthread_mutex_lock(&mutex);
worktodo=1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
void killthread
{
runthread=NO;
}
thiton was correct. I couldnt kill the thread while it was blocked. Theres probably a better way to do this but the solution that worked for me was to set runthread to false then wake the thread.
void killthread
{
runthread=NO;
pthread_mutex_lock(&mutex);
worktodo=1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
You initialize runthread to NO and compare it to YES. The thread should never reach the inside of its
while(runthread==YES)
loop. Besides, when the thread waits for work, killthread will not wake it up and runthread will stay in its work-waiting loop.
Related
in main, I create two threads
thread 1 for the first func
thread 2 for second func2 (it included while(1))
i try to stop func2 from func by using pthread_cancel()
but didn't work and after I finish with func the Linux return to func2 and continue the infinite loop
is there a way to stop a thread that worked with an infinite loop from another thread ????
I think you need pthread_exit();
#include <pthread.h>
void pthread_exit(void *rval_ptr);
So we see that this function accepts only one argument, which is the return from the thread that calls this function. This return value is accessed by the parent thread which is waiting for this thread to terminate. The return value of the thread terminated by pthread_exit() function is accessible in the second argument of the pthread_join which just explained above.
You can see this example below:
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
int ret1,ret2;
void* doSomeThing(void *arg)
{
unsigned long i = 0;
pthread_t id = pthread_self();
for(i=0; i<(0xFFFFFFFF);i++);
if(pthread_equal(id,tid[0]))
{
printf("\n First thread processing done\n");
ret1 = 100;
pthread_exit(&ret1);
}
else
{
printf("\n Second thread processing done\n");
ret2 = 200;
pthread_exit(&ret2);
}
return NULL;
}
int main(void)
{
int i = 0;
int err;
int *ptr[2];
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
else
printf("\n Thread created successfully\n");
i++;
}
pthread_join(tid[0], (void**)&(ptr[0]));
pthread_join(tid[1], (void**)&(ptr[1]));
printf("\n return value from first thread is [%d]\n", *ptr[0]);
printf("\n return value from second thread is [%d]\n", *ptr[1]);
return 0;
}
I created 2 buttons, one for start a new thread, the other to end it. The actual calculation inside the new thread involved new[] and delete[] so I don't abort the thread directly, but using a flag to end it. It may take some time to end the delete[] and result-saving, so I want the main thread to wait for the new thread to end. But however I tried, I find the new thread doesn't run(though its ThreadState is running) until the command lines for the stop-button are conducted. System::Threading::Thread works quite different from thread to me. Is it how it should be?
#include "stdafx.h"
ref class Form1 : System::Windows::Forms::Form
{
public:
//define a thread name and a flag to terminate the thread
System::Threading::Thread^ th1;
static bool ITP1=0;
Form1(void)
{InitializeComponent();}
System::Windows::Forms::Button^ ButtonStart;
System::Windows::Forms::Button^ ButtonStop;
System::Windows::Forms::Label^ Label1;
void InitializeComponent(void)
{
this->SuspendLayout();
this->ButtonStart = gcnew System::Windows::Forms::Button();
this->ButtonStart->Location = System::Drawing::Point(20, 20);
this->ButtonStart->Click += gcnew System::EventHandler(this, &Form1::ButtonStart_Click);
this->Controls->Add(this->ButtonStart);
this->ButtonStop = gcnew System::Windows::Forms::Button();
this->ButtonStop->Location = System::Drawing::Point(120, 20);
this->ButtonStop->Click += gcnew System::EventHandler(this, &Form1::ButtonStop_Click);
this->Controls->Add(this->ButtonStop);
this->Label1 = gcnew System::Windows::Forms::Label();
this->Label1->Location = System::Drawing::Point(20, 80);
this->Controls->Add(this->Label1);
this->ResumeLayout(false);
}
void ThreadStart()
{
for (int idx=0;idx<999999999;++idx)
{
if (ITP1) break;
}
this->Label1->Text = "finished";
ITP1=0;
}
System::Void ButtonStart_Click(System::Object^ sender, System::EventArgs^ e)
{
th1 = gcnew System::Threading::Thread(gcnew System::Threading::ThreadStart(this,&Form1::ThreadStart));
th1->Start();
this->Label1->Text = "running";
}
System::Void ButtonStop_Click(System::Object^ sender, System::EventArgs^ e)
{
if (th1->ThreadState==System::Threading::ThreadState::Running)
{
//use the flag to stop the thread
ITP1=1;
//the wait method using while+sleep doesn't work
while (th1->ThreadState==System::Threading::ThreadState::Running) System::Threading::Thread::Sleep(1000);
//replacing the wait method above with "th1->Join()" doesn't work either
}
}
};
int main()
{
Form1^ A1 = gcnew Form1();
A1->ShowDialog();
return 0;
}
You have to join() the called thread in the main thread. Then the main thread will wait until the called thread is finished.
See the documentation for Join to know how it is to be called.
Finally I found the cause. It's just the "this->" pointer in the new thread. Removing it makes everything OK.
I suppose it's because the Form allows operation on only one element at the same time. I ask the button-click to wait for the new thread, and the new thread tries to edit the other form element. They wait for each other to end and cause a dead loop.
I have the following situation
std::mutex m;
void t() {
//lock the mutex m here
}
main() {
//create thread t here
//lock the mutex m here
}
I would like the thread t() to acquire the mutex before main() does, how can I obtain this behaviour using the threading functions provided by C++11?
Putting simply an std::lock_guard inside main() and t() would not work because it can take a bit before the thread is spawned, an so the mutex can be locked by main().
Regarding the conditional variable that Sneftel mentioned in the comment section, and a somewhat similar solution to the one provided by Angew:
One possible solution:
std::condition_variable cv;
std::mutex m;
bool threadIsReady = false; //bool should be fine in this case
void t() {
std::unique_lock<std::mutex> g(m);
threadIsReady = true;
cv.notify_one();
}
int main() {
std::thread th(t);
//if main locks the mutex first, it will have to wait until threadIsReady becomes true
//if main locks the mutex later, wait will do nothing since threadIsReady would have already been true
std::unique_lock<std::mutex> g(m);
cv.wait(g, [] {return threadIsReady; });
}
Here's a quick & dirty way to achieve this effect:
std::atomic<bool> threadIsReady{false};
void t()
{
std::lock_guard<std::mutex> g(m);
threadIsReady = true;
}
main()
{
std::thread th(t);
while (!threadIsReady) {}
std::lock_guard<std::mutex> g(m);
}
In my c++11 project, I need to generate two threads which run infinitely. Here is an example:
static vector<int> vec;
static std::mutex mtx;
static std::condition_variable cond;
static bool done = false;
void f1()
{
while(!done)
{
// do something with vec and mtx
}
}
void f2()
{
while(!done)
{
// do something with vec and mtx
}
}
thread t1(f1);
thread t2(f2);
void finish(int s)
{
done = true;
// what should I do???
}
int main()
{
signal(SIGINT, finish);
t1.join();
t2.join();
return 0;
}
Normally, I won't stop or kill this program. But in case of exception, I think I need to do something for ctrl-c, which is used to kill the program. But I don't know how to quit this program properly.
If I'm right, t1 and t2 might continue executing even if the main has returned 0. So I think I need to make them detach like this:
void finish()
{
done = true;
t1.detach();
t2.detach();
}
However, when I execute the program and do ctrl-c, I get an error:
terminate called after throwing an instance of 'std::system_error'
I've found this link, so I think the problem is the same: mtx and/or cond has been destroyed while t1 or t2 hasn't finished yet.
So how could I kill the program properly? Or I don't need to deal with the signal ctrl-c and the program itself knows what to do to quit properly?
done should be std::atomic<bool>, or unsequenced reads/writes are not legal.
Accessing atomic variables is only safe in a signal handler if std::atomic<bool>::is_lock_free is true. Check that. If it isn't true, your program should probably abort with an error in main.
When you .join(), you wait for the thread to finish executing. And you don't want to exit main unless the threads have finished.
In short, do this:
static std::atomic<bool> done = false;
(rest of code goes here)
int main()
{
if (!done.is_lock_free()) return 10; // error
signal(SIGINT, finish);
t1.join();
t2.join();
}
I have just found that making marquee in the same thread it's text get stopped a little in a time when my application loads data..
I am asking if anybody has done marquee functionality in their application in a seperate thread using TTimer.
Even in you do the marquee in a thread, you still have to synchronize it with the main thread for display, so you will still have the same problem if you continue doing lengthy data loads in the main thread. So do the data loading in a separate thread instead, and leave the marquee (and all other UI elements and logic) in the main thread, where it belongs. You should not be doing blocking operations in the main thread to begin with.
HANDLE hThread;
DWORD ThreadId;
int Data_Of_Thread_1 = 1;
unsigned long __stdcall ThreadFunc(void *Arg)
{
int a=0;
while(a != 100000000000000000)
{
a++;
Form1->ListBox1->Items->Add(a);
}
return 0;
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
// hThread=CreateThread(NULL,0,ThreadFunc,0,0,&ThreadId);
hThread = CreateThread( NULL, 0, ThreadFunc, &Data_Of_Thread_1, 0, &ThreadId);
if ( hThread == NULL)
{
ExitProcess(Data_Of_Thread_1);
}
}
void __fastcall TForm1::Button2Click(TObject *Sender)
{
TerminateThread(hThread,ThreadId);
}