操作系统创建线程

创建线程

int pthread_create (pthread_t* thread,
                    const pthread_attr_t* attr,
                    void* (*start_routine) (void*),
                    void* arg);
​
thread        - 线程ID,输出型参数。我们目前使用的Linux中pthread_t即unsigned long int
attr          - 线程属性,NULL表示缺省属性,如果没有特殊需求,一般写NULL即可
start_routine - 线程入口函数指针,参数和返回值的类型都是void*
                启动线程本质上就是调用一个函数,只不过是在一个独立的线程中调用的,函数返回即线程结束
arg           - 传递给线程过程函数的参数
返回值:成功返回0,失败返回错误码,但不会修改全局的错误变量,也就是无法使用perror获取错误原因。    
 
注意:
    1、restrict: C99引入的编译优化指示符,提高重复解引用同一个指针的效率。
    2、应设法保证在线程过程函数执行期间,其参数所指向的目标持久有效。
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
​
void* run(void* arg)
{
    for(;;)
    {
        printf("#");
        fflush(stdout);
        sleep(1);
    }
}
​
int main(int argc,const char* argv[])
{
    pthread_t tid;
    int ret = pthread_create(&tid,NULL,run,NULL);
    printf("%d %lu\n",ret,tid);
​
    for(;;)
    {
        printf("*");
        fflush(stdout);
        sleep(1);
    }
        
    return 0;
}

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值