Click here to Skip to main content
14,456,133 members

Why does the main thread crashes when a child thread invokes call back function of main thread

Member 13508014 asked:

Open original thread
I am trying to understand some basics of multi threading. I have written a simple program as shown below. When the child thread invokes a call back function, a crash is seen in the main thread (here the scope of call back function is in main thread. That's what I understand the scope is. But I am guessing it is something related to scope that is leading to crash)

#include <iostream>
#include <thread>

using namespace std;

void t1_exec(void (*notfiy_func)());
void main_observer();

int main()
{
	std::thread t1(t1_exec, main_observer);
	int i = 0;
	while (i < 200)
	{
		i++;
		cout << "In main thread" << endl;
	}

	return (0);
}

void t1_exec(void (*notify_func)())
{
	int i = 0;
	while (i < 5)
	{
		i++;
		cout << "Inside T1" << endl;
	}

	notify_func();
	
}

void main_observer()
{
	cout << "Inside Observer" << endl;

	exit(1);
}


What I have tried:

Tried to increase the time of execution of main thread by increasing the number of loop (i.e increased i to 2000). Still didn't help stopping crash.
Tags: C++, multi-threading

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100