如何在普通 C 中启动线程? [英] How do I start threads in plain C?

查看:18
本文介绍了如何在普通 C 中启动线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C 中使用了 fork() 来启动另一个进程.我如何开始一个新线程?

I have used fork() in C to start another process. How do I start a new thread?

推荐答案

既然你提到了 fork() 我假设你在一个类 Unix 系统上,在这种情况下 POSIX 线程(通常称为 pthread)是您想要使用的.

Since you mentioned fork() I assume you're on a Unix-like system, in which case POSIX threads (usually referred to as pthreads) are what you want to use.

具体来说,pthread_create() 是创建新线程所需的函数.它的参数是:

Specifically, pthread_create() is the function you need to create a new thread. Its arguments are:

int  pthread_create(pthread_t  *  thread, pthread_attr_t * attr, void *
   (*start_routine)(void *), void * arg);

第一个参数是返回的线程 id 指针.第二个参数是线程参数,除非您想以特定优先级启动线程,否则它可以为 NULL.第三个参数是线程执行的函数.第四个参数是执行时传递给线程函数的单个参数.

The first argument is the returned pointer to the thread id. The second argument is the thread arguments, which can be NULL unless you want to start the thread with a specific priority. The third argument is the function executed by the thread. The fourth argument is the single argument passed to the thread function when it is executed.

这篇关于如何在普通 C 中启动线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆