#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *f1(void *p)
{
system("./while.exe");
}
main()
{
int i=0;
int k=3;
int j=0;
void *status
while(i<k)
{
thread_id = pthread_create(&thread_handler, NULL, &f1,NULL);
pthread_join(thread_pram_play_handler, &status);
//if(((int *)status)==0)
i++;
}//while
while(1)
{
printf("\nEnte value ");
scanf("%d",&j);
if(j==1)
{
system("pkill while.exe");
}
}
}
While.c 包含:
#include<stdio.h>
main()
{
int i=0;
for(i=0;i<25;i++)
{
printf("\nHI");
}
}
在这里,我只是编写与我的实际代码类似的代码。 我的要求 1. 我想在另一个线程完成后执行三个线程。 2. 我想在使用 pkill 之间终止它。
使用 pthread_join 我可以一个接一个地执行线程,但无法杀死线程。
如果我没有使用 pthread_join,那么线程会同时执行并能够杀死它们。我认为它正在阻塞进程。
我无法满足我的要求。所以要么我必须改变线程执行方式,要么必须改变终止线程的方式。
谢谢
任何帮助将不胜感激。
最佳答案
I want to execute three threads one after the completion of another.
那么你就根本不需要线程了。这一要求违背了多线程的目的。
If I am not using pthread_join then threads are executing simultaneously and able to kill them.I think it is blocking the process.
是的,由于主线程被阻塞在pthread_join()
处(等待使用pthread_create()
创建完成),所以它没有机会执行您的 pkill
命令。 system()
会阻塞,直到命令完成,这又会阻塞在 pthread_join()
处等待的主线程。
基本上你的两个要求是相互矛盾的。您可以做的最接近的事情是使用 &
在后台运行“命令”:
system("./while.exe &");
以便 system()
立即返回,并且主线程可以继续并能够运行 pkill
命令。但这种方法可以满足您的要求,在实际编程中没有多大意义。
关于c - 如何在另一个线程完成后执行另一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46263255/