Linux C应用编程-5-线程

各线程共享的进程资源和环境

  • 进程同一地址空间
  • 同一进程定义的函数和全局变量
  • 文件描述符表
  • 每种信号的处理方式(SIG_IGNSIG_DFL或者自定义的信号处理函数)
  • 当前工作目录
  • 用户id和组id

线程各自独立的资源

  • 线程id
  • 上下文,包括各种寄存器的值、程序计数器和栈指针
  • 栈空间
  • errno变量
  • 信号屏蔽字
  • 调度优先级

1.创建线程

#include <stdio.h>
#include <stdlib.h>
//线程所需要的头文件
#include <pthread.h>
//getpid需要的头文件
#include <unistd.h>

//线程编译需要加上-lpthread

int temp = 0;

void printids(char *s)
{
    pid_t pid;
    pthread_t tid;
    
    pid = getpid();
    tid = pthread_self();//获取当前线程id
    //由于pthread_t并不是一个整型,所以需要做强制类型转换
    printf("%s pid:%d, tid:%u\n", s, pid, (unsigned int)tid);
    
}

//线程处理函数
void  *thread_handler(void *arg)
{
    static int value = 0;
    
    temp++; //线程间共享全局变量、局部变量、函数
    value++;
    printf("%s value:%d, temp:%d\n", (char*)arg, value, temp);
    
    printids(arg);
    return NULL;
}

int main(void)
{
    pthread_t tid;
    int err;
    
    /*
     * 返回线程id
     * 线程属性设置
     * 线程处理函数
     * 线程处理函数参数
     */
    err = pthread_create(&tid, NULL, thread_handler, "new_thread1");
    //pthread_create失败返回错误码
    if (err != 0) {
        //由于pthread_create的错误码不保存在errno中,因此不能直接用perror()打印错误信息
        fprintf(stderr, "pthread_create1\n");
        exit(1);
    }
    printf("create tid %u\n", (unsigned int)tid);
    
    err = pthread_create(&tid, NULL, thread_handler, "new_thread2");
    //pthread_create失败返回错误码
    if (err != 0) {
        //由于pthread_create的错误码不保存在errno中,因此不能直接用perror()打印错误信息
        fprintf(stderr, "pthread_create2\n");
        exit(1);
    }
    printf("create tid %u\n", (unsigned int)tid);
    
    printids("main_thread");
    sleep(2);//预留线程调度的时间
    return 0;
}

2.终止线程

只终止某个线程可以有三种方法:

  • 从线程函数return。这种方法对主线程不适用,从main函数return相当于调用exit
  • 一个线程可以调用pthread_cancel终止同一进程中的另一个线程。
  • 线程可以调用pthread_exit终止自己。

1)终止某个线程

#include <pthread.h>

void pthread_exit(void *value_ptr);
/*
成功返回0,失败返回错误号
*/

2)自身线程挂起

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值