[linux]进程(八)---线程概念

线程

概念:
线程自己基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计数器,一组寄存器和栈),
进程的所有信息对该进程的所有线程是共享的,包括程序文本,程序的全部内存,堆,栈和文件描述符。

线程标识:
进程ID在整个系统中是唯一的,用pid_t数据类型表示,
线程ID只在它所属的进程环境中有效,用pthread_t数据类型表示,用 pthread_t pthread_self(void);来获得自身线程ID。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <pthread.h>
 4 
 5 int main(){
 6     pthread_t thread_id;
 7 
 8     thread_id=pthread_self(); // 返回调用线程的线程ID
 9     printf("Thread ID: %lu.
",thread_id);
10 
11     if (pthread_equal(thread_id,pthread_self())) {
12 //    if (thread_id==0) {
13         printf("Equal!
");
14     } else {
15         printf("Not equal!
");
16     }
17     return 0;
18 }


线程的创建:
使用pthread_creat()函数:返回值:成功-0,失败-返回错误编号,可以用strerror(errno)函数得到错误信息

#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)//执行函数的参数  


线程的终止:
线程从执行函数返回,返回值是线程的退出码
线程被同一进程的其他线程取消
调用pthread_exit()函数退出。这里不是调用exit,因为线程调用exit函数,会导致线程所在的进程退出。
线程创建,线程终止实例:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;
int num = 0;
void *add(void *arg)
{
	
	int i = 0, tmp;
	for(;i<10;i++)
	{
		pthread_mutex_lock(&mylock);
		tmp=num+1;
		num=tmp;
		printf("add result is :%d
",num);
		pthread_mutex_unlock(&mylock);
	}
	return ((void*)0);
}

void *sub(void *arg)
{
	int i=0,tmp;
	for(;i<10;i++)
	{
		pthread_mutex_lock(&mylock);
		tmp=num-1;
		num=tmp;
		printf("sub result is:%d
",num);
		pthread_mutex_unlock(&mylock);
	}
	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_creat error :%s
",strerror(err));
		exit(-1);
	}
	err=pthread_create(&tid2,NULL,sub,NULL);
	if(err != 0)
	{
		printf("pthread_creat error :%s
",strerror(err));
		exit(-1);
	}
	err=pthread_join(tid1,&tret);
	if (err != 0)
	{
		printf("can not join with thread1: %s
",strerror(err));
	}
	printf("thread 1 exit code
");
	err=pthread_join(tid2,&tret);
	printf("thread 2 exit code 
");
	return 0;
}


编译的时候需要加上-lpthread,

2,线程同步:

点击打开链接

(一)互斥量:
两种方式初始化,第一种:赋值为常量PTHREAD_MUTEX_INITIALIZER;第二种,当互斥量为动态分配是,使用pthread_mutex_init函数进行初始化,使用pthread_mutex_destroy函数销毁。

#include<pthread.h>   
int pthread_mutex_init (pthread_mutex_t *__mutex,  
                   __const pthread_mutexattr_t *__mutexattr);  
int pthread_mutex_destroy (pthread_mutex_t *__mutex);  

#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,失败-错误编号
加解锁
加锁调用pthread_mutex_lock,解锁调用pthread_mutex_unlock。
[cpp] view plaincopyprint?
#include<pthread.h>   
int pthread_mutex_lock (pthread_mutex_t *__mutex);  
int pthread_mutex_unlock (pthread_mutex_t *__mutex);


使用互斥量应该避免死锁,如一个线程试图对同一个互斥量加锁两次,自身会陷入死锁状态,另外一个情况是一个程序中
一个线程占用一个互斥量但是试图获取第二个互斥量,但是另外一个线程已经占用第二个互斥量但是试图获取第一个互斥量。
可以用pthread_mutex_trylock()函数防止死锁
具体说一下trylock函数, 这个函数是非阻塞调用模式, 也就是说, 如果互斥量没被锁住, trylock函数将把互斥量加锁, 并获得对共享资源的访问权限;
 如果互斥量被锁住了, trylock函数将不会阻塞等待而直接返回EBUSY, 表示共享资源处于忙状态

(二)读写锁

#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
",i);  
#endif   
        ret=pthread_cond_wait(&qready,&mylock);//该函数把线程放入等待条件的线程列表,然后对互斥锁进行解锁,这两部都是原子操作。并且在pthread_cond_wait返回时,互斥量再次锁住。   
        if(ret==0)  
        {  
#ifdef DEBUG   
            printf("thread %d wait success
",i);  
#endif   
        }else  
        {  
#ifdef DEBUG   
            printf("thread %d wait failed:%s
",i,strerror(ret));  
#endif   
        }  
    }  
    printf("thread %d is running 
",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
",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
", i,strerror(err));  
            exit(-1);  
        }  
    }  
    return 0;  
}



(三)条件变量
为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。

原文地址:https://www.cnblogs.com/zhiliao112/p/4051372.html