线程控制

POSIX线程库(用户级)

与线程有关的函数构成了一个完整的系列,绝大多数函数的名字以“pthread_”开头
要使用这些函数库,要通过引入头文
链接这些线程函数库时要使用编译器命令的“-lpthread”选项
用户线程和内核线程是1对1的

一、线程创建
  • pthread_create函数
头文件:#include<pthread.h>
函数原型:int pthread_create(pthread_t * thread,const pthread_attr_t *attr,void *(*start_routine)(void*),void *arg);
函数功能:创建一个新的线程
返回值:成功返回0,失败返回错误码
参数:
thread:返回线程ID
attr:设置线程的属性,attr为NULL表示使用默认属性
start_routine:是一个函数地址。线程启动后要执行的函数
arg:传给线程启动函数的参数

pthread_t 无符号长整型

下面是创建线程代码的具体实现:

#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<pthread.h>
void *thread_run(void *arg)
{
    while(1)
    {
        printf("new pthread,thread is : %u,pid :%d\n",pthread_self(),getpid());
        sleep(1);
    }
}
int main()
{
    pthread_t tid;
    pthread_create(&tid,NULL,thread_run,NULL);
    while(1)
    {
        printf("main pthread,thread is : %u,pid %d\n",pthread_self(),getpid());
        sleep(3);
    }
    return 0;
}

按照正常写Makefile的方法写会出现下面的问题

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值