LInux C++多线程编程基础(汇总)

本文介绍了Linux环境下C++的多线程编程基础,包括线程创建、线程属性、pthread_join和pthread_exit的使用。还提到了C++11中的thread类,使得线程操作更简洁,但join时线程执行顺序未被保证。
摘要由CSDN通过智能技术生成

1. 前言

    本次来写一篇关于C++多线程的基本使用。前面有一篇是互斥锁的入门,学了两天,做一下总结。


2. 多线程

    (1) 创建

多线程的表示pthread_t:

/* Thread identifiers.  The structure of the attribute type is not
   exposed on purpose.  */
typedef unsigned long int pthread_t;

在源码中,pthread_t实际上就只是一个无符号的long int变量,用于线程的唯一标识符。

下面是pthread_create的原型:

/* Create a new thread, starting with execution of START-ROUTINE
   getting passed ARG.  Creation attributed come from ATTR.  The new
   handle is stored in *NEWTHREAD.  */
extern int pthread_create (pthread_t *__restrict __newthread,
			   const pthread_attr_t *__restrict __attr,
			   void *(*__start_routine) (void *),
			   void *__restrict __arg) __THROWNL __nonnull ((1, 3));

参数介绍:

    __newthread表示线程的唯一标识符

    __attr表示线程的属性,之后会介绍几个小方面的

    __*(*__start_rountine)(void *)这个实际上就是一个函数的指针

    __arg表示函数的参数,需要将其转化成void*指针才可以传值

线程创建之后如果不进行其他的操作,那么线程会在主线程结束的时候就结束,主线程不会等到所有线程结束后才结束,例如下面的代码:

#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t count_nonzero;
unsigned count;

void* decrement_count(void* data)
{
    pthread_mutex_lock(&mut);

    while(count == 0)
    {
        printf("1\n");
        pthread_cond_wait(&count_nonzero,&mut);
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值