I am trying to write a Teamcenter ITK program that will run as a different thread invoked from a main thread. The main thread is invoked from an action on the UI. Since the child thread takes a lot of time to complete, if I don't create the child thread and put the code in the main thread, the UI freezes for up to 10 minutes, which is not acceptable.
Both the main and child thread need to share authentication which was done by the main thread, since I am using SSO. They also need to connect to the database. Lastly, the main thread should not wait for the child thread to complete, since else the whole purpose of having the child thread will be defeated.
The code to invoke child thread is this:
handle = (HANDLE) _beginthread (submitToPublishTibcoWf, 0, &input); // create thread
do
{
sprintf(message, "Waiting %d time for 1000 milliseconds since threadReady is %d\n", i++, threadReady);
log_msg(message);
WaitForSingleObject(handle, 1000);
}
while (!threadReady);
sprintf(message, "Wait for thread to be ready over after %d tries since threadReady is %d\n", i, threadReady);
log_msg(message);
log_msg("Main thread about to exit now");
I set the threadReady = 1
global variable whenever I am about to execute the piece of code in the child thread that takes 8 minutes to run.
The problem is that the child thread is behaving weirdly after the main thread has exited, and I get this error:
Fri May 25 11:34:46 2012 : Main thread about to exit now
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Most of the child thread executes but sometimes it just crashes towards the very end.
To prevent exiting of the child thread, we can use detaching to make child process independent and not expected to join to parent. Thus we should not join child process and after that, we have to detach from main thread:
pthread_create(th, attr, what);
pthread_detach(th);
// and never join
Also:
threadReady
. Instead use condition variables in pthread
or another signaling methods like gObject
.