Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

passing thread data structure #21

Closed
Immortal-guard opened this issue Aug 26, 2021 · 1 comment
Closed

passing thread data structure #21

Immortal-guard opened this issue Aug 26, 2021 · 1 comment

Comments

@Immortal-guard
Copy link

Immortal-guard commented Aug 26, 2021

hi and thanks for this great job
I have a structure that im allocating memory for each thread and finally each thread has their own data structure for executing function
but I don't know how to pass their own thread_data while the task is in queue and I don't know which thread will execute it

struct thread_data
{
    /* some stuff */
};

void func(thread_data* data, int x)
{
	/* some stuff */
}

int main(int argc, char** argv)
{
	int num_thread = 4;

	thread_data* data = (thread_data*)malloc(num_thread * sizeof(thread_data)); // struct array for each thread
	if (data == NULL) return 1;

	thread_pool pool(num_thread);

	for (auto i = 1; i <= 100; i++)
		pool.push_task(func, &data[0], i); // !HERE! &data[0], &data[1], ... ?

	return 0;
}

if two or more threads are using the same structure, program crashes, they should have their own unique structure. How to solve this problem?

@Immortal-guard Immortal-guard changed the title passing thread data structure to thread pool passing thread data structure Aug 26, 2021
@bshoshany
Copy link
Owner

Sounds like you're having issues with data races. See a discussion here under "Threads and data races". There are several standard ways to handle this, such as using std::atomic or std::mutex. Both are used in the thread pool's code, so you are welcome to check it out as an example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants