Reputation: 1611
I have 2 threads. My goal is that the first one that terminate his own execution, have to stop the other thread. Is it possible?
I have this code:
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
void* start1(void* arg)
{
printf("I'm just born 1\n");
int i = 0;
for (i = 0;i < 100;i++)
{
printf("Thread 1\n");
}
printf("I'm dead 1\n");
pthread_exit(0);
}
void* start2(void* arg)
{
printf("I'm just born 2\n");
int i = 0;
for (i = 0;i < 1000;i++)
{
printf("Thread 2\n");
}
printf("I'm dead 2\n");
pthread_exit(0);
}
void* function()
{
int k = 0;
int i = 0;
for (i = 0;i < 50;i++)
{
k++;
printf("I'm an useless function\n");
}
}
int main()
{
pthread_t t, tt;
int status;
if (pthread_create(&t, NULL, start1, NULL) != 0)
{
printf("Error creating a new thread 1\n");
exit(1);
}
if (pthread_create(&tt, NULL, start2, NULL) != 0)
{
printf("Error creating a new thread 2\n");
exit(1);
}
function();
pthread_join(t, NULL);
pthread_join(tt, NULL);
return 0;
}
For example the first thread have to stop the second one. How can is possible to do that?
Upvotes: 2
Views: 2544
Reputation: 675
Pass as arguments to the 2 threads the thread id of the other. Than call pthread_kill(other_thread_id, SIGKILL)
in the first that finishes his work. I assume you know what you are doing (you've already been warned that this is bad practice).
Upvotes: 0
Reputation: 16148
This sounds like very complex (bad) design. Usually you would have a master (controller) and it would have children.
If you must take this approach I would make the first thread spawn the second, then the second the thrid (so that it "owns" that thread).
Finally if you must do it this way you can pass the thread to the first worker by it's void* argument.
Also you do not need to explicitly exit the thread, just let it 'run off' then join it.
Upvotes: 0
Reputation: 25601
Generally it's not good practice to force a thread to terminate. The clean way to terminate another thread is by setting a flag (visible to both threads) that tells the thread to terminate itself (by returning/exiting immediately).
Upvotes: 10