Every Time I run this Code I got the following Console output:
Attached to Thread
Attached to Thread
Detached from Process
Detached from Process
The whole process lasts about 4 ms.
I think the main problem is the printing the thread information to the console.
Is there a way to prevent it?
void acq(int i)
{
}
void run2Threads()
{
thread t0(acq, 0);
thread t1(acq, 1);
t0.join();
t1.join();
}
Related
I have a server listening to some port, and I create several detached threads.
Not only the server it self will run forever, but also the detached threads will run forever.
//pseudocode
void t1_func()
{
for(;;)
{
if(notified from server)
dosomething();
}
}
thread t1(t1_func);
thread t2(...);
for(;;)
{
// read from accepted socket
string msg = socket.read_some(...);
//notify thread 1 and thread 2;
}
Since I am new to multithreading, I don't know how to implement such nofity in server, and check the nofity in detached threads.
Any helpful tips will be appreciated.
The easiest way to do this is with std::condition_variable.
std::condition_variable will wait until another thread calls either notify_one or notify_all on it and only then will it wake up.
Here is your t1_func implemented using condition variables:
std::condition_variable t1_cond;
void t1_func()
{
//wait requires a std::unique_lock
std::mutex mtx;
std::unique_lock<std::mutex> lock{ mtx };
while(true)
{
t1_cond.wait(lock);
doSomething();
}
}
The wait method takes a std::unique_lock but the lock doesn't have to be shared to notify the thread. When you want to wake up the worker thread from the main thread you would call notify_one or notify_all like this:
t1_cond.notify_one();
If you want to have the thread wake up after a certain amount of time you could use wait_for instead of wait.
I am trying to create a new process from an existing process.
like that parentMain process creates childMain process.
my goal is:
1) Both process will continue running (means no one should wait for another to finish)
2) The creator - parentMain process, should send a message to the created process - childMain process.
I do not know when the new childMain process is actually ready. I can not use the wait function as I understood it waits until
the child process should end, but my aim is it will continue to run.
After little googling I am using the fork & exec family functions as follows:
void parentMain::CreateAndSend()
{
createNewProcess();
sendMessage();
}
void parentMain::createNewProcess()
{
char* param1[10] = "param1";
// Create new process.
cpid = fork();
if (cpid >= 0) // fork() succeeded.
{
if (cpid == 0) // 0 for child process.
{
execl("/home/kon/childMain", "/home/kon/childMain", param1, (char*)0);
}
else /* parent process */
{
printf("Parent process, parent PID=%d child PID=%d, getpid(), cpid);
}
}
else // fork() failed.
{
printf("Failure");
}
}
void parentMain::sendMessage()
{
Y = 50; // milliseconds.
nanosleep(Y);
?? isChildReady ??
sendChildMessage();
}
Now, sometimes sendMessage() fails!
if I am using a sleep(X) it succeeded. (in seconds)
but I want to reduce the time as much as I can.
How much time it takes to a process to be created?
is there any function that says "child is ready"?
How can I do it?
Thanks
The user interface has a button Start that when clicked launches a worker thread and the thread does:
- starts local bluetooth radio.
- start searching for remote radios.
while worker thread is doing that I would like to display a progress bar. Here is my plan:
void MyFrame::OnStart(wxCommandEvent& event)
{
/* launch worker thread */
int count = 0;
bool bSkip = false;
while (1)
{
wxProgressBar *p_pb = new wxProgressBar(...);
count++;
Sleep(500);
/* update progress bar to new value */
p_pb->update(count, wxStringEmpty, &bSkip);
/* need a way to get out of here when the worker thread is done */
}
}
/* custom event, fired when bluetooth is done */
void MyFrame::OnBluetoothSearchDone(wxCommandEvent& event)
{
/* we know the thread is done because this event is fired */
/* get data (if any) from the bluetooth module */
}
as you can see after I fire the worker thread the main UI thread is stuck in the progressbar loop and will never catch the event that is sent by the worker thread.
if there is a way to check for pending events then I can do that in the progressbar loop and if there is then I can breakout? OR maybe call the update method on the progressbar from an idle function??
There is no such such thing as wxProgressBar in wxWidgets. If you're using wxProgressDialog and its Update() method, events should be already dispatched because it calls wxYield() internally. If you don't, you can either do it yourself -- but make sure you understand the dangers of doing this! -- or, better, avoid entering a loop at all and just disable the elements of the UI that can't be used and use a timer to update the progress indicator.
I am not sure if my question is correct, but I have the following example, where the main thread creates two additional threads.
Since I am not using join command at the end of the main, it will continue execution and in the same time, the two created threads will work in parallel. But since the main is terminated before they finish their execution, I am getting the following output:
terminate called without an active exception
Aborted (core dumped)
Here's the code:
#include <iostream> // std::cout
#include <thread> // std::thread
#include <chrono>
void foo()
{
std::chrono::milliseconds dura( 2000 );
std::this_thread::sleep_for( dura );
std::cout << "Waited for 2Sec\n";
}
void bar(int x)
{
std::chrono::milliseconds dura( 4000 );
std::this_thread::sleep_for( dura );
std::cout << "Waited for 4Sec\n";
}
int main()
{
std::thread first (foo);
std::thread second (bar,0);
return 0;
}
So my question is how to keep these two threads working even if the main thread terminated?
I am asking this because in my main program, I have an event handler ,and for each event I create a corresponding thread. But the main problem when the handler creates a new thread, the handler will continue execution. Until it is destroyed which will cause also the newly created thread to be destroyed. So my question is how to keep the thread alive in this case?
Also if I use a join it will convert back to serialization.
void ho_commit_indication_handler(message &msg, const boost::system::error_code &ec)
{
.....
}
void event_handler(message &msg, const boost::system::error_code &ec)
{
if (ec)
{
log_(0, __FUNCTION__, " error: ", ec.message());
return;
}
switch (msg.mid())
{
case n2n_ho_commit:
{
boost::thread thrd(&ho_commit_indication_handler, boost::ref(msg), boost::ref(ec));
}
break
}
};
Thanks a lot.
Keeping the threads alive is a bad idea, because it causes a call to std::terminate. You should definitively join the threads:
int main()
{
std::thread first (foo);
std::thread second (bar, 0);
first.join();
second.join();
}
An alternative is to detach the threads. However you still need to assert that the main thread lives longer (by e.g. using a mutex / condition_variable).
This excerpt from the C++11 standard is relevant here:
15.5.1 The std::terminate() function [except.terminate]
1 In some situations exception handling must be abandoned for less subtle error
handling techniques. [ Note: These situations are:
[...]
-- when the destructor or the copy assignment operator is invoked on an
object of type std::thread that refers to a joinable thread
Hence, you have to call either join or detach on threads before scope exit.
Concerning your edit: You have to store the threads in a list (or similar) and wait for every one of them before main is done. A better idea would be to use a thread pool (because this limits the total number of threads created).
I'm writing a simple application that should be able to receive and process notifications in a background thread using Apple's CoreFoundation framework. Here is what I'm trying to accomplish:
static void DummyCallback(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo) {
printf("RECEIVED NOTIFICATION\n");
}
void *ThreadStart(void *arg) {
CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
NULL,
&DummyCallback,
NULL,
CFSTR("TEST_OBJECT"),
CFNotificationSuspensionBehaviorDeliverImmediately);
printf("background thread: run run loop (should take 5 sec to exit)\n");
int retval = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 5, true);
printf("background thread: exited from run loop (retval: %d)\n", retval);
return NULL;
}
int main(int argc, char** argv) {
pthread_t thread;
int rc = pthread_create(&thread, NULL, &ThreadStart, NULL);
assert(rc == 0);
printf("main: sleep\n");
sleep(10);
printf("main: done sleeping\n");
return 0;
}
If I run the program I just get
main: sleep
background thread: run run loop (should take 5 sec to exit)
background thread: exited from run loop (retval: 1)
main: done sleeping
The problem is that the background thread's run loop exits immediately (return code kCFRunLoopRunFinished instead of kCFRunLoopRunTimedOut) because there is no source/observer/timer. CFNotificationCenterAddObserver registers itself only with the run loop of the main thread but not the one of my background thread.
I need the main thread for some other stuff and can't use it to run it's run loop. Is there any way to get this working? Maybe by registering CFNotificationCenter with the run loop of the background thread?
Thanks in advance!
As stated in http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFNotificationCenterRef/Reference/reference.html
The first time an observer is registered with a distributed notification center, the notification center creates a connection with the system-wide notification server and places a listening port into the common modes of the current thread’s run loop. When a notification is delivered, it is processed on this initial thread, even if the observer that is receiving the notification registered for the notification on a different thread.
Because loaded frameworks may potentially spawn threads and add their own observers before your code executes, you cannot know for certain which thread will receive distributed notifications. If you need to control which thread processes a notification, your callback function must be able to forward the notification to the proper thread. You can use a CFMessagePort object or a custom CFRunLoopSource object to send notifications to the correct thread’s run loop.