【问题标题】:Creating multiple threads and invoking other exectuables in Cygwin through system()?通过 system() 在 Cygwin 中创建多个线程并调用其他可执行文件?
【发布时间】:2010-10-31 01:02:30
【问题描述】:

我正在 Cygwin 中进行一个项目。为了尝试在 C 中创建多个线程,并且每个线程使用 system() 函数通过命令行调用另一个可执行文件,结果发现事情没有正常工作。具体来说,我的代码是这样的:

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
  long tid;
  tid = (long)threadid;
  system("date ");
  pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
  pthread_t threads[NUM_THREADS];
  int rc;
  long t;

  for(t=0; t<NUM_THREADS; t++){
    printf("In main: creating thread %ld\n", t);
    rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
    if (rc){
       printf("ERROR; return code from pthread_create() is %d\n", rc);
       exit(-1);
    }
  }
  pthread_exit(NULL);
}

但它不起作用。我得到的错误是堆栈溢出的分段错误。无论如何,对如何通过创建多个线程并行调用系统外壳中的其他可执行文件有一个想法? 谢谢。

【问题讨论】:

  • 代码没有明显的问题,在linux上运行良好。作为一个在黑暗中的镜头,您是否与 -pthreads、-lpthreads 等链接?

标签: c cygwin pthreads executable


【解决方案1】:

添加此代码:

for(t=0; t<NUM_THREADS; t++){
  pthread_join(threads[t], NULL);
}

之前

pthread_exit(NULL);

main()中调用。

【讨论】:

    【解决方案2】:

    这里有几个错误:

    1. 在 main() 函数中,创建线程后,应使用 pthread_exit() 退出所有单个线程。所以 exit() 的使用不在这里。

    2. 在 main() 函数的最后,在您终止主线程之前,调用 pthread_join() 以等待所有单个线程终止。

    3. 在所有子线程都终止后,可以调用exit()自行终止进程。

    http://www.thegeekstuff.com/2012/04/terminate-c-thread/

    【讨论】:

      【解决方案3】:

      这个问题看起来值得向 Cygwin 邮件列表报告。

      您可以做的是取消线程并使用fork()/exec()spawn(_P_NOWAITO, ...) 创建子进程。

      (spawn() 实际上是一个函数族;有关详细信息,请参阅/usr/include/process.h。建议使用它,因为它避免了 Cygwin 的高分叉开销。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-19
        • 1970-01-01
        • 1970-01-01
        • 2020-12-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多