c - 可附加线程和可分离线程的主要区别是什么。是否与 CPU 开销有关

标签 c pthreads

pthread_t tid;
pthread_create(&tid, NULL, thr_loop, NULL);

如果我除了传递 NULL 之外传递一些值会发生什么?

最佳答案

嗯,根据manpage最后一个参数是用户定义的参数,它被传递给新线程调用的函数。

 static void *
   thread_start(void *arg)
   {
       struct thread_info *tinfo = arg;
       char *uargv, *p;

       printf("Thread %d: top of stack near %p; argv_string=%s\n",
               tinfo->thread_num, &p, tinfo->argv_string);

       uargv = strdup(tinfo->argv_string);
       if (uargv == NULL)
           handle_error("strdup");

       for (p = uargv; *p != '\0'; p++)
           *p = toupper(*p);

       return uargv;
   }

然后他们调用 pthread_create 如下

pthread_create(&tinfo[tnum].thread_id, &attr,&thread_start, &tinfo[tnum]);

正如你所看到的,有一个参数传递给函数,然后传递给函数 到 thread_start 函数。你可以在这里传递你喜欢的一切。

更新:

我刚刚看到,您可能还提到了其他一些 NULL 值。所以让我也解释一下:

  1. PTHREAD_CREATE_DETACHED - 如果调用线程不想等待已创建线程的终止,您应该使用此状态创建它。
  2. PTHREAD_CREATE_JOINABLE - 假定您正在以某种方式等待线程,例如pthread_join

为了进一步阅读,我可以推荐 this网页。

关于c - 可附加线程和可分离线程的主要区别是什么。是否与 CPU 开销有关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32110248/

相关文章:

c++ - 使用 pthread_win32 增加进程优先级

c++ - 当守护线程在后台工作时返回一个函数 (c++)

c - 将字符串中的一个字母替换为另一个字母

计算总 sizeof 参数的 C 函数

c++ - 递归函数中在堆上分配与在堆栈上分配

c - 学习c从strtok中获取位置指针作为int

c - 为什么运行此函数时会出现段错误?

c - C 中的线程间通信

mysql - 多线程访问MySQL错误

c++ - 在简单的 pthread 中运行服务器