一、什麼是線程?
線程是進程的一個實體,是CPU調度和分派的基本單位,它是比進程更小的能獨立運行的基本單位。線程自己基本上不擁有系統資源,只擁有一點在運行中必不可少的資源(如程序計數器,一組寄存器和棧),但是它可與同屬一個進程的其他的線程共享進程所擁有的全部資源。
二、什麼時候使用多線程?
三、線程的創建
#include<pthread.h>
int pthread_create (pthread_t *__restrict __newthread,//新創建的線程ID
__const pthread_attr_t *__restrict __attr,//線程屬性
void *(*__start_routine) (void *),//新創建的線程從start_routine開始執行
void *__restrict __arg)//執行函數的參數
返回值:成功-0,失敗-返回錯誤編號,可以用strerror(errno)函數得到錯誤信息四、線程的終止
- 線程從執行函數返回,返回值是線程的退出碼
- 線程被同一進程的其他線程取消
- 調用pthread_exit()函數退出。這裏不是調用exit,因爲線程調用exit函數,會導致線程所在的進程退出。
一個小例子:
啓動兩個線程,一個線程對全局變量num執行加1操作,執行五百次,一個線程對全局變量執行減1操作,同樣執行五百次。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
int num=0;
void *add(void *arg) {//線程執行函數,執行500次加法
int i = 0,tmp;
for (; i <500; i++)
{
tmp=num+1;
num=tmp;
printf("add+1,result is:%d\n",num);
}
return ((void *)0);
}
void *sub(void *arg)//線程執行函數,執行500次減法
{
int i=0,tmp;
for(;i<500;i++)
{
tmp=num-1;
num=tmp;
printf("sub-1,result is:%d\n",num);
}
return ((void *)0);
}
int main(int argc, char** argv) {
pthread_t tid1,tid2;
int err;
void *tret;
err=pthread_create(&tid1,NULL,add,NULL);//創建線程
if(err!=0)
{
printf("pthread_create error:%s\n",strerror(err));
exit(-1);
}
err=pthread_create(&tid2,NULL,sub,NULL);
if(err!=0)
{
printf("pthread_create error:%s\n",strerror(err));
exit(-1);
}
err=pthread_join(tid1,&tret);//阻塞等待線程id爲tid1的線程,直到該線程退出
if(err!=0)
{
printf("can not join with thread1:%s\n",strerror(err));
exit(-1);
}
printf("thread 1 exit code %d\n",(int)tret);
err=pthread_join(tid2,&tret);
if(err!=0)
{
printf("can not join with thread1:%s\n",strerror(err));
exit(-1);
}
printf("thread 2 exit code %d\n",(int)tret);
return 0;
}
使用g++編譯該文件(g++ main.cpp -o main)。此時會報錯undefined reference to `pthread_create'。
報這個錯誤的原因是:pthread庫不是linux默認的庫,所以在編譯時候需要指明libpthread.a庫。
解決方法:在編譯時,加上-lpthread參數。
執行結果:
乍一看,結果是對的,加500次,減500次,最後結果爲0。但是仔細看所有的輸出,你會發現有異樣的東西。
導致這個不和諧出現的原因是,兩個線程可以對同一變量進行修改。假如線程1執行tmp=50+1後,被系統中斷,此時線程2對num=50執行了減一操作,當線程1恢復,在執行num=tmp=51。而正確結果應爲50。所以當多個線程對共享區域進行修改時,應該採用同步的方式。
五、線程同步
1、互斥量
#include<pthread.h>
int pthread_mutex_init (pthread_mutex_t *__mutex,
__const pthread_mutexattr_t *__mutexattr);
int pthread_mutex_destroy (pthread_mutex_t *__mutex);
返回值:成功-0,失敗-錯誤編號#include<pthread.h>
int pthread_mutex_lock (pthread_mutex_t *__mutex);
int pthread_mutex_unlock (pthread_mutex_t *__mutex);
void *add(void *arg) {
int i = 0,tmp;
for (; i <500; i++)
{
pthread_mutex_lock(&mylock);
tmp=num+1;
num=tmp;
printf("+1,result is:%d\n",num);
pthread_mutex_unlock(&mylock);
}
return ((void *)0);
}
void *sub(void *arg)
{
int i=0,tmp;
for(;i<500;i++)
{
pthread_mutex_lock(&mylock);
tmp=num-1;
num=tmp;
printf("-1,result is:%d\n",num);
pthread_mutex_unlock(&mylock);
}
return ((void *)0);
}
2、讀寫鎖
允許多個線程同時讀,只能有一個線程同時寫。適用於讀的次數遠大於寫的情況。#include<pthread.h>
int pthread_rwlock_init (pthread_rwlock_t *__restrict __rwlock,
__const pthread_rwlockattr_t *__restrict
__attr);
int pthread_rwlock_destroy (pthread_rwlock_t *__rwlock);
返回值:成功--0,失敗-錯誤編號int pthread_rwlock_rdlock (pthread_rwlock_t *__rwlock)
寫加鎖:
int pthread_rwlock_wrlock (pthread_rwlock_t *__rwlock)
解鎖用同一個函數:
int pthread_rwlock_unlock (pthread_rwlock_t *__rwlock)
3、條件變量
int pthread_cond_init (pthread_cond_t *__restrict __cond,
__const pthread_condattr_t *__restrict
__cond_attr);
int pthread_cond_destroy (pthread_cond_t *__cond);
條件等待
pthread_cond_wait (pthread_cond_t *__restrict __cond,
pthread_mutex_t *__restrict __mutex)
這裏需要注意的是,調用pthread_cond_wait傳遞的互斥量已鎖定,pthread_cond_wait將調用線程放入等待條件的線程列表,然後釋放互斥量,在pthread_cond_wait返回時,再次鎖定互斥量。int pthread_cond_signal (pthread_cond_t *__cond);
int pthread_cond_broadcast (pthread_cond_t *__cond)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#define DEBUG 1
int num=0;
pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t qready=PTHREAD_COND_INITIALIZER;
void * thread_func(void *arg)
{
int i=(int)arg;
int ret;
sleep(5-i);//線程睡眠,然最先生成的線程,最後甦醒
pthread_mutex_lock(&mylock);//調用pthread_cond_wait前,必須獲得互斥鎖
while(i!=num)
{
#ifdef DEBUG
printf("thread %d waiting\n",i);
#endif
ret=pthread_cond_wait(&qready,&mylock);//該函數把線程放入等待條件的線程列表,然後對互斥鎖進行解鎖,這兩部都是原子操作。並且在pthread_cond_wait返回時,互斥量再次鎖住。
if(ret==0)
{
#ifdef DEBUG
printf("thread %d wait success\n",i);
#endif
}else
{
#ifdef DEBUG
printf("thread %d wait failed:%s\n",i,strerror(ret));
#endif
}
}
printf("thread %d is running \n",i);
num++;
pthread_mutex_unlock(&mylock);//解鎖
pthread_cond_broadcast(&qready);//喚醒等待該條件的所有線程
return (void *)0;
}
int main(int argc, char** argv) {
int i=0,err;
pthread_t tid[4];
void *tret;
for(;i<4;i++)
{
err=pthread_create(&tid[i],NULL,thread_func,(void *)i);
if(err!=0)
{
printf("thread_create error:%s\n",strerror(err));
exit(-1);
}
}
for (i = 0; i < 4; i++)
{
err = pthread_join(tid[i], &tret);
if (err != 0)
{
printf("can not join with thread %d:%s\n", i,strerror(err));
exit(-1);
}
}
return 0;
}
在非DEBUG模式,執行結果如圖所示:
在DEBUG模式可以看出,線程3先被喚醒,然後執行pthread_cond_wait(輸出thread 3 waiting),此時在pthread_cond_wait中先解鎖互斥量,然後進入等待狀態。這是thread 2加鎖互斥量成功,進入pthread_cond_wait(輸出thread 2 waiting) ,同樣解鎖互斥量,然後進入等待狀態。直到線程0,全局變量與線程參數i一致,滿足條件,不進入條件等待,輸出thread 0 is running。全局變量num執行加1操作,解鎖互斥量,然後喚醒所有等待該條件的線程。thread 3 被喚醒,輸出thread 3 wait success。但是不滿足條件,再次執行pthread_cond_wait。如此執行下去,滿足條件的線程執行,不滿足條件的線程等待。