结束gcc C Linux中第一个成功的线程

我是一位经验丰富的C程序员,以前从未使用过线程或并行。 我一直在读它,但我没有看到我想要的例子。

我在Mac和Linux上使用gcc C编译器。 我想在我的系统中用一个新的过程X2替换一个重要的过程X,它将启动两个方法,因为只要机器有多个CPU,这两天就会在两个不同的处理器上运行(大多数情况下都是这样)。

这两种方法可能共享一些全局变量,但它们不会写入除自己的堆栈之外的任何内存位置。 他们每个人都会调用系统中的许多其他程序。 我没有想到任何其他并行处理。

一旦任何一个线程完成,那就是它! 这就是答案。 X2应该立即杀死另一个线程并将答案返回给任何调用X2的人。

也许我天真但我认为这是一个众所周知的线程使用。 示例代码请!

我建议尝试以下程序。 它使用两个Linux进程来运行由父进程创建的两个过程。 只要一个孩子完成,父母就会得到通知并终止另一个孩子。 研究包含部分中出现的系统调用的文档当然是理解代码所必需的。

// fork #include  // wait, kill #include  // wait #include  // kill #include  // exit #include  //printf #include  void proc( int id) { int seed= id; int count= rand_r( &seed) % 10; printf( "\nprocess[%d]: taking %d steps.", id, count); int i; for ( i= 1; i <= count; ++i) { printf( "\nprocess[%d]: step #%d", id, i); sleep( 1); } printf( "\nprocess[%d]:\tfinished.", id); exit( 1); } int main( int argc, char* argv[]) { // create 1st child process pid_t p1= fork(); if ( 0 == p1) proc( 1); // child does not return // create 2nd child process pid_t p2= fork(); if ( 0 == p2) proc( 2); // child does not return // this is the parent process // wait for a child to terminate pid_t p_terminated= wait( NULL); // declare result // terminate the other child if ( p1 == p_terminated) { puts( "\nparent: \tprocess[1] finished first."); kill( p2, SIGKILL); } if ( p2 == p_terminated) { puts( "\nparent: \tprocess[2] finished first."); kill( p1, SIGKILL); } } 

在我的机器上,程序产生以下输出:

 process[1]: taking 3 steps. process[2]: taking 7 steps. process[1]: step #1 process[2]: step #1 process[1]: step #2 process[2]: step #2 process[1]: step #3 process[2]: step #3 process[1]: finished. parent: process[1] finished first. 

这两个进程可以同时完成,以便它们都打印出“已finished ”的消息,但即使在这种情况下,父进程也会声明其中一个成为第一个,并终止另一个进程。