【问题标题】:Issue with muilti-threading with pthread: thread is executing prematurelypthread 的多线程问题:线程过早执行
【发布时间】:2021-12-24 04:32:47
【问题描述】:

我正在尝试将线程调用到子进程正在运行的函数中的另一个函数。我首先调用一个子进程,该子进程生成另一个子进程,而子进程又生成一个线程。但是,线程函数一直过早地执行。可能是什么问题?

#define _GNU_SOURCE
#include <sched.h>
#include <pthread.h> // pthread
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>// waitpid
#include <sys/wait.h> //waitpid
#define STACK_Size 1024*1024

void* print(void* ptr)
{ 
  printf("\n4. In thread\n");
  char* message;
  message = (char*)ptr;
  printf("\n5. Message from parent: %s \n\n",message);
}

static int threading(void * ptr)
{ 
  char* message;
  message = (char*)ptr;
  printf("\n3. In child process 2\n");
  pthread_t Tid;
  pthread_create(&Tid,NULL,&print,(void*)message);
  pthread_join(Tid,NULL);
  printf("\n6. Thread done.... exiting child process 2\n\n");
}


static int child(void *ptr)
{
  char* message;
  message = (char*) ptr;
  print("\n2. In child 1");
  // creating child process
  char* stack_ptr = malloc(STACK_Size);
  unsigned long flags =0;
   pid_t pid;
   pid = clone(threading, stack_ptr+STACK_Size,flags | SIGCHLD,message);
    int status;
    waitpid(pid,&status,0);
    printf("7. Done with child 2\n\n8. Now exiting child process 1\n"); 
}

int main(int argc, char ** argv)
{
 char msg[150];
 printf("1. Currently in main program name: %s\n", argv[0]);
 sprintf(msg,"The name of the program is (%s), P.S this is parent (pid:%d)",argv[0],getpid());
 char* stack_pointer = malloc(STACK_Size);
 unsigned long flags =0;
 setbuf(stdout,NULL);
 if((argc >1) && (strcmp(argv[1],"vm")==0))
 {
  flags = CLONE_VM;
 }
 pid_t pid;
 pid = clone(child,stack_pointer+STACK_Size,flags | SIGCHLD,msg);
 int status;
 waitpid(pid,&status,0);
 printf("\n9. Done with Parent process\n");
}

这是它产生的输出:

1. Currently in main program name: ./clone
    
4. In thread
    
5. Message from parent: 
2. In child 1 
    
    
3. In child process 2
    
4. In thread
    
5. Message from parent: The name of the program is (./clone), P.S this is parent (pid:15159) 
    
    
6. Thread done.... exiting child process 2
    
7. Done with child 2
    
8. Now exiting child process 1
    
9. Done with Parent process

【问题讨论】:

  • 您是否以某种方式强制执行命令?如果没有,则无法保证何时运行。启动的线程可能在启动它的调用甚至返回之前完成。另外,你的描述很混乱。特别是,我想知道您是否无法删除多处理。另外,你为什么一开始就将它与线程混合?作为这里的新用户,也请带上tour并阅读How to Ask
  • 启动一个线程然后立即加入它是没有意义的,就像你的threading() 函数所做的那样。几乎所有方式都直接调用线程函数会更好。
  • 你为什么使用 Linux 特定的 clone() 而不是 POSIX 标准的 fork()?前者更灵活一些,但便携性较差且更难正确使用,而且您没有利用任何增加的灵活性。
  • “继续过早执行” 究竟是什么意思?你希望发生什么?

标签: c linux multithreading pthreads posix


【解决方案1】:

如果过早执行的意思是在2. 之前打印包含4.5. 的行,那是因为您调用自定义print() 函数来输出2. (print("\n2. In child 1")),这也是打印出4.5.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多