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(&coun