Linux 线程

进程: 资源分配的基本单位

线程: 进程调度的基本单元  

线程强调 资源共享 但不是一味的共享        线程两个比较重要的私有成员:【1】必须有自己的硬件上下文 进行自己切换时 上下文的切换【2】私有栈结构

进程强调 资源独占 但不是一味的共享


各线程共享一下进程资源:

(1)文件描述符表

(2)每种信号的处理方式(SIG_IGN,SIG_DFL或者自定义的信号处理函数)

(3)当前工作目录

(4)用户id和组id


每个线程自己私有的数据:

(1)线程id

(2)上下文,包括各种寄存器的值、程序计数器和栈指针

(3)栈空间

(4)errno变量

(5)信号屏蔽字

(6)调度优先级


(地址空间就是资源)

只要进程能够共享地址空间 并且分别执行共享空间的一部分 就将这些进程叫做线程

wKioL1edPPzyI1bzAACcTg17Xvc004.png

在Linux中 进程 就是 地址空间只有一个PCB的线程  (单线程不能看成是 进程 因为线程的地址空间 可以对应多个PCB)

所以Linux中 所有的都可以看成是 线程          进程看成是 独占资源的线程 线程是轻量级的进程

Linux编程是不支持线程的 ,但可以利用别人 提供的库 来实现线程编程

函数:

          

 1) int pthread_create(pthread_t *thread, const pthread_attr_t *attr,     void *(*start_routine) (void *), void *arg);

                  作用:  创建线程 

                  参数:pthrea_t *thread  用于返回线程id

                              const pthread_attr_t *attr  表示线程属性 可以传NULL

                              void *(*start_routine) (void *) 线程执行代码所在的 函数 的函数指针

                              void *arg  对应上面 void *(*start_routine) (void *) 函数 指针的用到的参数 void*

                    返回值:成功返回0     失败返回错误码 用strerror(错误码)将错误信息转化为字符串

          

  2)     void pthread_exit(void *retval);

     

           3)    int pthread_join(pthread_t thread, void **retval);

                        只有阻塞方式等待线程     线程必须等待防止内存 泄露

                         获得pthread_exit的retval返回值

 

       int pthread_detach(pthread_t thread);  // 分离

编译时 由于线程是POSIX库的 所以 要在后面加上 -lpthread 

否则 报错

gcc -o pthread_creat pthread_creat.c
/tmp/ccPkLaUo.o: In function `main':
pthread_creat.c:(.text+0x71): undefined reference to `pthread_create'
collect2: ld 返回 1
make: *** [pthread_creat] 错误 1

因为他在

libpthread共享库中

gcc -o pthread_creat pthread_creat.c -lpthread

1) 创建线程:

练习代码:

#include<stdio.h>
#include <pthread.h>
#include <stdlib.h>
void* thread_run(void *arg)
{
    printf("%s: \npid is :%d, tid is : %u\n",(char*)arg,getpid(), pthread_self( ));
    sleep(20);
    //return (void*)256; // 线程的退出码可以超过255 进程的256 是0 NULL;
    pthread_exit(NULL);
//exit(3);  _exit(3) 这个所有线程 全部结束

}
int main()
{
    pthread_t id;
    int ret = pthread_create(&id, NULL, thread_run,"new thread run...");// NULL);
    if (ret == 0)
    {
        printf("create thread success\n");
    }
    else
    {
        printf("create thread error! info is :%s\n", strerror(ret));
        exit(ret);
    }
    while (1)
    {
        printf("main thread run...\n");
        sleep(5);
    }
    return 0;
}
运行结果:
[bozi@localhost thread]$ ./pthread_creat
create thread success
main thread run...
new thread run...:
pid is :4418, tid is : 3077688176
main thread run...
main thread run...

命令行查看:

[bozi@localhost test_20160726]$ ps -aL
 [bozi@localhost ~]$ ps -aL
  PID   LWP TTY          TIME CMD
 3114  3114 pts/5    00:00:00 vim
 3171  3171 pts/5    00:00:00 man
 3174  3174 pts/5    00:00:00 sh
 3175  3175 pts/5    00:00:00 sh
 3179  3179 pts/5    00:00:00 less
 4418  4418 pts/1    00:00:00 pthread_creat
 4418  4419 pts/1    00:00:00 pthread_creat
 4420  4420 pts/0    00:00:00 ps
32098 32098 pts/6    00:00:00 vim

LWP轻量级进程    cpu调度不以PID进程为基本单位 而以LWP(线程)为基本单位  【PID可以相同的多个存在 但 LWP不一样 多线程】

LWP在整个操作系统有效 但 线程中调用的 pthread_self()得到的 线程id只在当前进程有效 看不到全局的  全局的LWP才是操作系统级别的。

由上面结果:PID4418由两个 以PID区分线程是区分不开的  但以LWP全局的线程ID是可以区分开的  但是要注意 在线程中调用pthread_self()得到的 线程id

                    tid is : 3077688176与这个4418 4419是比一样的 且 pthread_self()得到的只能在线程内部看到 是一个局部性的


2)线程退出

在线程中 不要调用exit exit会终止整个 进程

线程退出:(1)调用return 退出码

               (2)调用pthread_exit(退出码)

3) 终止线程

3种方法:

     1 从线程return 不适合main线程 main线程return 相当于调用exit

     2 一个线程调用 pthread_cancel终止同一进程中的另一个线程

     3 线程调用pthread_exit来终止自己

4)线程等待

函数:       int pthread_join(pthread_t thread, void **retval)

成功返回0 失败返回错误号

pthread_join得到的 进程的终止状态有3种

1 thread线程通过 return返回 value_ptr所指的空间存返回值

2 thread线程被别的线程调用pthread_cancel异常终止,value_ptr所指的空间存常数 'PTHREAD_CANCELED'

【grep -ER 'PTHREAD_CANCELED' /usr/include/

线程被取消 一定退出码为 -1     这个-1其实是一个宏 PTHREAD_CANCELED -1

[bozi@localhost test_20160726]$ grep -ER 'PTHREAD_CANCELED' /usr/include/

/usr/include/pthread.h:#define PTHREAD_CANCELED ((void *) -1)

/usr/include/pthread.h:   the thread as per pthread_exit(PTHREAD_CANCELED) if it has been】

3 thread线程自己调用pthread_exit终止 value_ptr所指的空间存pthread_exit的参数

练习代码:

#include<stdio.h>
#include <stdlib.h>
#include <pthread.h>
// return 返回
void* pthread1(void *_val)
{
    printf("thread 1 returning...\n");
    return (void*)1;
}
// pthread_exit返回
void* pthread2(void *_val)
{
    printf("thread 2 exiting...\n");
    pthread_exit((void*)2);
}
// 被其他进程 cancel
void* pthread3(void * _val)
{
    while (1)
    {
        printf("phread 3 is running, wait for be cancel...\n");
        sleep(1);
    }
    return NULL;
}
int main()
{
    pthread_t tid;
    void *tret;
    // thread 1 return
    pthread_create(&tid, NULL, pthread1,NULL);
    pthread_join(tid, &tret);
    printf("thread1 return , thread id is :%u, return code is :%d\n", (unsigned long)tid, (int)tret);
    //thread 2 exit
    pthread_create(&tid, NULL, pthread2, NULL);
    pthread_join(tid, &tret);
    printf("thread2 exit , thread id is: %u, exit code is :%d\n ",(unsigned long)tid, (int)tret);
    // thread 3 cancel by other
    pthread_create(&tid, NULL, pthread3, NULL);
    sleep(3);
    pthread_cancel(tid);
    pthread_join(tid, &tret);
    printf("thread3 cancel,thread id is :%u, cancel code is :%d\n", (unsigned long)tid, (int)tret);
    return 0;
}

运行结果:

[bozi@localhost thread]$ ./pthread_join
thread 1 returning...
thread1 return , thread id is :3077725040, return code is :1
thread 2 exiting...
thread2 exit , thread id is: 3077725040, exit code is :2
 phread 3 is running, wait for be cancel...
phread 3 is running, wait for be cancel...
phread 3 is running, wait for be cancel...
thread3 cancel,thread id is :3077725040, cancel code is :-1

5)线程分离

用 pthread_detach

       int pthread_detach(pthread_t thread);

线程也可以被置为 detach 状态, 这样的线程一旦终止就立刻回收它占用的所有资源 ,

而不保留终止状态。不能对一个已经处于 detach状态的线程调用 pthread_join,这样的调用将

返回EINVAL。 对一个尚未 detach的线程调用 pthread_joinpthread_detach 都可以把该线程

置为detach状态 ,也 就是说 ,不能对同一线程调用两次 pthread_join,或者如果已经对一个线程调

用 了 pthread_detach就不能再调用pthread_join了。


在任何一个时间点上, 线程是可结合的( joinable)或者是分离的(detached。一个可

结合的线程能够被其他线程收回其资源和杀死。在被其他线程回收之前,它的存储器资源

(例如栈)是不释放的。相反,一个分离的线程是不能被其他线程回收或杀死的,它的存

储器 资源在它终止时由系统自动释放。


线程退出 将退出信息保存在 线程PCB中 

return进程 建议在 非主线程中调用     因为主线程的退出比较特殊  主线程退出 相当于进程退出  其他线程也就退出

在代码中定义的 全局变量 进程之间都可以 共享 这样 线程间 通信比进程之间的通信简单的多 

thread_detach 分离出去的线程 还是 属于进程的 因为 他的资源是进程提供的 在进程中 如果他调用exit 那么主进程 还是会 退出的

默认情况下,线程被创建成可结合的。 为了避免存储器泄漏,每个可结合线程都应该要

么被显示地回收,即调用 pthread_join;要么通过调用 pthread_detach函数被分离。

如果一个可结合线程结束运行但没有被 join,则它的状态类似于进程中的 Zombie Process,

即还有一部分资源没有被回收,所以创建线程者应该调用 pthread_join来等待线程运行结

束,并可得到线程的退出代码,回收其资源。

由于调用 pthread_join后,如果该线程没有运行结束,调用者会被阻塞 ,在有些情况下我

们并不希望如此。例如,在 Web服务器中当主线程为每个新来的连接请求创建一个子线程进

行处理的时候,主线程并不希望因为调用 pthread_join而阻塞(因为还要继续处理之后到来

的连接请求),

两种 detach的方法:

这时可以在子线程中加入代码

pthread_detach(pthread_self())

或者父线程调用

pthread_detach(thread_id)(非阻塞,可立即返回)


这将该子线程的状态设置为分离的( detached),如此一来,该线程运行结束后会自动释

放所有资源。

练习代码:

#include<stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_run(void * _val)
{
    //分离线程方法1  子线程 方法中 分离
//    pthread_detach(pthread_self());
    printf("thread  detached\n");
    printf("%s\n", (char*)_val);
    return NULL;
}
int main()
{
    pthread_t tid;
    int tret = pthread_create(&tid, NULL, thread_run, "thread1 run...");
    //分离线程方法2 主线程中 分离子线程
    pthread_detach(tid);   
    if (tret != 0)
    {
        printf("create thread error!, info is :%s\n", strerror(tret));
        return tret;
    }
    // wait
    int ret = 0;
    sleep(1);
    if (0 == pthread_join(tid, NULL))
    {
        printf("pthread wait success!\n");
        ret = 0;
    }
    else
    {
        printf("pthread wait falied!\n");
        ret = 1;
    }
    return ret;
}

运行结果;

[bozi@localhost thread]$ ./pthread_detach
thread  detached
thread1 run...
pthread wait falied!

6)线程同步:

(1)互斥量

对于多线程的程序 ,访问冲突的问题是很普遍的 ,解决的办法是引入互斥锁 (Mutex,Mutual

Exclusive Lock),获得锁的线程可以完成 -修改 - 的操作, 然后释放锁给其它线程 ,没有获得

锁的线程只能等待而不能访问共享数据 ,这样 - 修改- 三步操作组成一个原子操作 ,要么

都执行 ,要么都不执行 ,不会执行到中间被打断 ,也不会在其它处理器上并行做这个操作。


测试出现问题的代码(没对临界资源加锁):

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
static int g_count = 0;
void * read_write_mem(void * _val)
{
    int val = 0;
    int i = 0;
    for (; i < 5000; i++)
    {
        val = g_count;
        printf("pthread id is %x, count is : %d\n", (unsigned long)pthread_self(), g_count); // printf 里面用到系统调用,因为显示器是外设,对外设的操作一定是操作系统。  这样就能产生进入内核的条件
          // 让内核进行其他工作的 这样就会出现问题 使得对 g_count 的操作不是原子的 
        g_count = val + 1;
        //g_count++;
    }
    return NULL;
}
int main()
{
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, read_write_mem, NULL);
    pthread_create(&tid2, NULL, read_write_mem, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    printf("count final val is : %d\n", g_count);
    return 0;
}

运行结果:

pthread id is b77d4b70, count is : 5176
pthread id is b77d4b70, count is : 5177
pthread id is b77d4b70, count is : 5178
pthread id is b77d4b70, count is : 5179
pthread id is b77d4b70, count is : 5180
pthread id is b77d4b70, count is : 5181
count final val is : 5182

解决:

用到的函数:

       int pthread_mutex_lock(pthread_mutex_t *mutex);
       int pthread_mutex_trylock(pthread_mutex_t *mutex);
       int pthread_mutex_unlock(pthread_mutex_t *mutex);
       #include <pthread.h>
       int pthread_mutex_destroy(pthread_mutex_t *mutex);
       int pthread_mutex_init(pthread_mutex_t *restrict mutex,
              const pthread_mutexattr_t *restrict attr);
       pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

一个线程可以调用 pthread_mutex_lock获得Mutex,如果这时另一个线程已经调用

pthread_mutex_lock获得了该Mutex,则当前线程需要挂起等待 ,直到另一个线程调用

pthread_mutex_unlock释放Mutex,当前线程被唤醒 ,才能获得该Mutex并继续执行。

如果一个线程既想获得锁 ,又不想挂起等待 ,可以调用 pthread_mutex_trylock, 如果Mutex

经被 另一个线程获得 ,这个函数会失败返回 EBUSY, 而不会使线程挂起等待。


代码:

void * read_write_mem(void * _val)
{
    int val = 0;
    int i = 0;
    for (; i < 5000; i++)
    {
        pthread_mutex_lock(&mutex_lock); // 加锁
        val = g_count;
        printf("pthread id is %x, count is : %d\n", (unsigned long)pthread_self(), g_count);
        g_count = val + 1;
        pthread_mutex_unlock(&mutex_lock);
        //g_count++;
    }
    return NULL;
}
int main()
{
    pthread_mutex_init(&mutex_lock,NULL);
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, read_write_mem, NULL);
    pthread_create(&tid2, NULL, read_write_mem, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    printf("count final val is : %d\n", g_count);
    pthread_mutex_destroy(&mutex_lock);
    return 0;
}

运行:

...
pthread id is b77e5b70, count is : 9995
pthread id is b77e5b70, count is : 9996
pthread id is b77e5b70, count is : 9997
pthread id is b77e5b70, count is : 9998
pthread id is b77e5b70, count is : 9999
count final val is : 10000

加锁的实现:

由于 汇编层面 支持 exchange  这条指令是原子的 交换两个数的值

所以 就有了 加锁操作的实现

加锁建议; 能不加锁 就不加锁       万不得已加锁,以最简洁的方式加锁 ,避免复杂,降低产生死锁的条件。

(2) 条件变量 

完成同步

用到的函数:

   int pthread_cond_destroy(pthread_cond_t *cond);
       int pthread_cond_init(pthread_cond_t *restrict cond,
              const pthread_condattr_t *restrict attr);
       pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
       int pthread_cond_timedwait(pthread_cond_t *restrict cond,
              pthread_mutex_t *restrict mutex,
              const struct timespec *restrict abstime);
       int pthread_cond_wait(pthread_cond_t *restrict cond,
              pthread_mutex_t *restrict mutex);
       int pthread_cond_broadcast(pthread_cond_t *cond);
       int pthread_cond_signal(pthread_cond_t *cond);

一个Condition Variable 总是 和一个 Mutex搭配使用

pthread_cond_wait在一个Condition Variable上阻塞,函数需要做以下三步:

1)释放Mutex【因为之前申请 锁 如果自己直接阻塞 那么生产者也就得不到锁 所以要先释放锁】

2) 阻塞等待

3)当被唤醒时,重新获得Mutex并返回

 

生产者消费者

1)两个角色 消费者 和 消费者角色( 线程担当)

2)1中生产场所 (在这是链表)

3)3个条件 生产者-生产者(互斥) 消费者-消费者(互斥)   消费者-生产者(同步)

练习代码【LIFO模式 后进先出】:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct _list
{
    struct _list *_next;
    int _val;
}product_list;
product_list* head = NULL;
static pthread_mutex_t lock;
static pthread_cond_t cond;
void init_list(product_list *list)
{
    if (list != NULL)
    {
        list->_next = NULL;
        list->_val = 0;
    }
}
void* consumer(void * _val)
{
    product_list *p = NULL;
    while (1)
    {
        pthread_mutex_lock(&lock);
        while (head == NULL)
        {
            pthread_cond_wait(&cond, &lock);
        }
        p = head;
        head = head->_next;
        p->_next = NULL;
        pthread_mutex_unlock(&lock);
        printf("consum success, val is : %d\n", p->_val);
        free(p);
        p = NULL;
    }
    return NULL;
}
void* product(void *_val)
{
    while (1)
    {
        sleep(1);
        product_list *p = malloc(sizeof(product_list));
        pthread_mutex_lock(&lock);
        init_list(p);
        p->_val = rand()%1000;
        p->_next = head;
        head = p;
        pthread_mutex_unlock(&lock);
        printf("call consumer! product success , val is : %d\n",head->_val);
        pthread_cond_signal(&cond);
    }
}
int main()
{
    pthread_mutex_init(&lock, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_t t_product;
    pthread_t t_consumer;
    pthread_create(&t_product, NULL, product, NULL);
    pthread_create(&t_consumer, NULL, consumer, NULL);
    pthread_join(t_product, NULL);
    pthread_join(t_consumer, NULL);
    return 0;
}

运行结果:

[bozi@localhost test_20160730]$ ./consumer_producter
call consumer! product success , val is : 383
consum success, val is : 383
call consumer! product success , val is : 886
consum success, val is : 886
call consumer! product success , val is : 777
consum success, val is : 777
call consumer! product success , val is : 915
consum success, val is : 915
call consumer! product success , val is : 793
consum success, val is : 793

练习代码【FIFO模式 先进先出】

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
/*LIFO*/
typedef struct _list
{
    struct _list *_next;
    int _val;
}product_list;
product_list* head = NULL;
static pthread_mutex_t lock;
static pthread_cond_t cond;
void init_list(product_list *list)
{
    if (list != NULL)
    {
        list->_next = NULL;
        list->_val = 0;
    }
}
static print_list(product_list * l)
{
    while (l != NULL)
    {
        printf("%d->", l->_val);
        l = l->_next;
    }
    printf("over\n");
}
void* consumer(void * _val)
{
    // 每次消费最后一个
    product_list *p = NULL;
    while (1)
    {
        sleep(2);
        pthread_mutex_lock(&lock);
        while (head == NULL)
        {
            printf("wait for product\n");
            pthread_cond_wait(&cond, &lock);
        }
        p = head;
        if (p == NULL)
        {
            pthread_mutex_unlock(&lock);
        }
        else if (p->_next == NULL )
        {
            head = NULL;
            printf("consum success, val is : %d\n", p->_val);
            pthread_mutex_unlock(&lock);
            free(p);
        }
        else
        {
            while(p->_next->_next != NULL)
            {
                p = p->_next;
            }
            printf("consum success, val is : %d\n", p->_next->_val);
            pthread_mutex_unlock(&lock);
            free(p->_next);
            p->_next = NULL;
        }
        print_list(head);
    }
    return NULL;
}
void* product(void *_val)
{
    while (1)
    {
        sleep(1);
        product_list *p = malloc(sizeof(product_list));
        pthread_mutex_lock(&lock);
        init_list(p);
        p->_val = rand()%1000;
        p->_next = head;
        head = p;
        pthread_mutex_unlock(&lock);
        printf("call consumer! product success , val is : %d\n",head->_val);
        pthread_cond_signal(&cond);
    }
}
int main()
{
    pthread_mutex_init(&lock, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_t t_product;
    pthread_t t_consumer;
    pthread_create(&t_product, NULL, product, NULL);
    pthread_create(&t_consumer, NULL, consumer, NULL);
    pthread_join(t_product, NULL);
    pthread_join(t_consumer, NULL);
    return 0;
}

运行:

[bozi@localhost test_20160730]$ ./consumer_producter_multi
call consumer! product success , val is : 383
consum success, val is : 383
over
call consumer! product success , val is : 886
call consumer! product success , val is : 777
consum success, val is : 886
777->over
call consumer! product success , val is : 915
call consumer! product success , val is : 793
consum success, val is : 777
793->915->over
call consumer! product success , val is : 335
call consumer! product success , val is : 386
consum success, val is : 915
386->335->793->over
call consumer! product success , val is : 492
call consumer! product success , val is : 649
consum success, val is : 793
649->492->386->335->over
call consumer! product success , val is : 421

练习代码【多消费者多生产者】:

#include <pthread.h>
/*LIFO*/
typedef struct _list
{
    struct _list *_next;
    int _val;
}product_list;
product_list* head = NULL;
static pthread_mutex_t lock;
static pthread_cond_t cond;
void init_list(product_list *list)
{
    if (list != NULL)
    {
        list->_next = NULL;
        list->_val = 0;
    }
}
static print_list(product_list * l)
{
    while (l != NULL)
    {
        printf("%d->", l->_val);
        l = l->_next;
    }
    printf("over\n");
}
void* consumer(void * _val)
{
    // 每次消费最后一个
    product_list *p = NULL;
    while (1)
    {
        sleep(2);
        pthread_mutex_lock(&lock);
        while (head == NULL)
        {
            printf("%s tid :%u wait for product\n",(char*)_val,pthread_self());
            pthread_cond_wait(&cond, &lock);
        }
        p = head;
        if (p == NULL)
        {
            pthread_mutex_unlock(&lock);
        }
        else if (p->_next == NULL )
        {
            head = NULL;
            printf("%s tid :%u consum success, val is : %d\n",(char*)_val, pthread_self(),p->_val);
            pthread_mutex_unlock(&lock);
            free(p);
        }
        else
        {
            while(p->_next->_next != NULL)
            {
                p = p->_next;
            }
            printf("%s tid :%u consum success, val is : %d\n",(char*)_val, pthread_self(), p->_next->_val);
            pthread_mutex_unlock(&lock);
            free(p->_next);
            p->_next = NULL;
        }
        print_list(head);
    }
    return NULL;
}
void* product(void *_val)
{
    while (1)
    {
        sleep(1);
        product_list *p = malloc(sizeof(product_list));
        pthread_mutex_lock(&lock);
        init_list(p);
        p->_val = rand()%1000;
        p->_next = head;
        head = p;
        pthread_mutex_unlock(&lock);
        printf("%s tid :%u call consumer! product success , val is : %d\n",(char*)_val, pthread_self(),head->_val);
        //pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
    }
}
int main()
{
    pthread_mutex_init(&lock, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_t t_product1;
    pthread_t t_product2;
    pthread_t t_consumer1;
    pthread_t t_consumer2;
    pthread_create(&t_product1, NULL, product, "p1");
    pthread_create(&t_product2, NULL, product, "p2");
    pthread_create(&t_consumer1, NULL, consumer, "c1");
    pthread_create(&t_consumer2, NULL, consumer, "c2");
    pthread_join(t_product1, NULL);
    pthread_join(t_product2, NULL);
    pthread_join(t_consumer1, NULL);
    pthread_join(t_consumer2, NULL);
    return 0;
}

运行:

[bozi@localhost test_20160730]$ make
gcc -o consumer_producter_multi consumer_producter_multi.c -lpthread
[bozi@localhost test_20160730]$ ./consumer_producter_multi
p2 tid :3067267952 call consumer! product success , val is : 383
p1 tid :3077757808 call consumer! product success , val is : 886
c1 tid :3056778096 consum success, val is : 383
886->over
c2 tid :3046288240 consum success, val is : 886
over
p2 tid :3067267952 call consumer! product success , val is : 777
p1 tid :3077757808 call consumer! product success , val is : 915
p2 tid :3067267952 call consumer! product success , val is : 793
p1 tid :3077757808 call consumer! product success , val is : 335
c1 tid :3056778096 consum success, val is : 777
335->793->915->over
c2 tid :3046288240 consum success, val is : 915
335->793->over
p2 tid :3067267952 call consumer! product success , val is : 386
p1 tid :3077757808 call consumer! product success , val is : 492
p2 tid :3067267952 call consumer! product success , val is : 649
p1 tid :3077757808 call consumer! product success , val is : 421
c1 tid :3056778096 consum success, val is : 793
421->649->492->386->335->over
c2 tid :3046288240 consum success, val is : 335
421->649->492->386->over
p2 tid :3067267952 call consumer! product success , val is : 362
p1 tid :3077757808 call consumer! product success , val is : 27
p2 tid :3067267952 call consumer! product success , val is : 690
p1 tid :3077757808 call consumer! product success , val is : 59

(3)Semaphore信号量

用到的函数:

      

 int sem_init(sem_t *sem, int pshared, unsigned int value);
               pshared为零 表示同一进程中的线程的同步
       int sem_wait(sem_t *sem);
       int sem_trywait(sem_t *sem);
       int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
       int sem_post(sem_t *sem);
       int sem_destroy(sem_t *sem);

用数组实现下面的循环链表

wKiom1edPSLzrWD_AACZ3bS3Lvk394.png

环形buf 生产者绝对不能将生产者 围一圈 这样就覆盖了别的数据

如何防止 覆盖

生产者 看重 space资源

消费者 看重 data资源

练习代码【单生产者单消费者】:不需要加互斥锁 因为一个生产者和一个消费者 是不会区域重叠的

#include<stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define _SEM_PRO_ 5
#define _SEM_COM_ 0
sem_t sem_product;
sem_t sem_consume;
int bank[_SEM_PRO_];
void* consumer(void * _val)
{
    int c = 0;
    while (1)
    {
     sem_wait(&sem_consume);
        int _consume = bank[c];
        bank[c] = -5;
        printf("consume done..., val is : %d\n", _consume);
        sem_post(&sem_product);// 增加生产者的信号量
        c = (c + 1) % _SEM_PRO_;
    //    sleep(rand()%5);
    }
}
void* producter(void *_val)
{
    int p = 0;
    while (1)
    {
         sem_wait(&sem_product);
        int _product = rand() % 100;
        bank[p] = _product;
        printf("product done..., val is : %d\n",_product);
        sem_post(&sem_consume);// 增加消费者的信号量
        p = (p + 1)% _SEM_PRO_;
        sleep(rand()%2);
    }
}
void destroy_all_sem()
{
    printf("\nprocess done ...\n");
    sem_destroy(&sem_product);
    sem_destroy(&sem_consume);
    exit(155);
}
void init_all_sem()
{
    signal(2, destroy_all_sem);
    int i = 0;
    for (; i < _SEM_PRO_; i++)
    {
        bank[i] = 0;
    }
    sem_init(&sem_product, 0, _SEM_PRO_);
    sem_init(&sem_consume, 0 , _SEM_COM_);
}
void run_product_consume()
{
    pthread_t tid_consumer;
    pthread_t tid_producter;
    pthread_create(&tid_consumer, NULL, consumer, NULL);
    pthread_create(&tid_producter, NULL, producter, NULL);
    //pthread_exit((void *)2);
    pthread_join(tid_consumer, NULL);
    pthread_join(tid_producter, NULL);
}
int main()
{
    init_all_sem();
    run_product_consume();
    destroy_all_sem();
    return 0;
}

运行:

[bozi@localhost test_20160730]$ ./Semaphore
product done..., val is : 83
product done..., val is : 77
consume done..., val is : 83
consume done..., val is : 77
product done..., val is : 93
consume done..., val is : 93
^C
process done ...


练习代码【多生产者 多消费者】 :   (在 单消费者 和 单消费者的基础上 加 互斥锁)

#include<stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define _SEM_PRO_ 5
#define _SEM_COM_ 0
sem_t sem_product;
sem_t sem_consume;
int bank[_SEM_PRO_];
    int conindex = 0;
    int proindex = 0;
static pthread_mutex_t con_lock;
static pthread_mutex_t pro_lock;
void* consumer(void * _val)
{
    while (1)
    {
        sem_wait(&sem_consume);
        // 保证对conindex的操作加锁就行
        pthread_mutex_lock(&con_lock);
        int c = conindex;
        conindex = (conindex + 1) % _SEM_PRO_;
        pthread_mutex_unlock(&con_lock);
        int _consume = bank[c];
        bank[c] = -5;
        printf("%s ----consume done..., val is : %d\n",(char*)_val, _consume);
        sem_post(&sem_product);// 增加生产者的信号量
        sleep(rand()%5);
    }
}
void* producter(void *_val)
{
    while (1)
    {
         sem_wait(&sem_product);
        // 保证对proindex的操作是加锁的
        pthread_mutex_lock(&pro_lock);
        int p = proindex;
        proindex = (proindex + 1)% _SEM_PRO_;
        pthread_mutex_unlock(&pro_lock);
        int _product = rand() % 100;
        bank[p] = _product;
        printf("%s ---product done..., val is : %d\n",(char*)_val,_product);
        sem_post(&sem_consume);// 增加消费者的信号量
        sleep(rand()%2);
    }
}
void destroy_all_sem()
{
    printf("\nprocess done ...\n");
    sem_destroy(&sem_product);
    sem_destroy(&sem_consume);
    exit(155);
}
void init_all_sem()
{
    signal(2, destroy_all_sem);
    int i = 0;
    for (; i < _SEM_PRO_; i++)
    {
        bank[i] = 0;
    }
    sem_init(&sem_product, 0, _SEM_PRO_);
    sem_init(&sem_consume, 0 , _SEM_COM_);
}
void run_product_consume()
{
    pthread_t tid_consumer1;
    pthread_t tid_producter1;
    pthread_t tid_consumer2;
    pthread_t tid_producter2;
    pthread_create(&tid_consumer1, NULL, consumer, "c1");
    pthread_create(&tid_consumer2, NULL, consumer, "c2");
    pthread_create(&tid_producter1, NULL, producter, "p1");
    pthread_create(&tid_producter2, NULL, producter, "p2");
    //pthread_exit((void *)2);
    pthread_join(tid_consumer1, NULL);
    pthread_join(tid_producter1, NULL);
    pthread_join(tid_consumer2, NULL);
    pthread_join(tid_producter2, NULL);
}
int main()
{
    pthread_mutex_init(&con_lock, NULL);
    pthread_mutex_init(&pro_lock, NULL);
    init_all_sem();
    run_product_consume();
    destroy_all_sem();
    pthread_mutex_destroy(&con_lock);
    pthread_mutex_destroy(&pro_lock);
    return 0;
}

运行:

[bozi@localhost test_20160730]$ make
gcc -o Semaphore_multi Semaphore_multi.c -lpthread
[bozi@localhost test_20160730]$ ./Semaphore_multi
p1 ---product done..., val is : 83
p1 ---product done..., val is : 77
p2 ---product done..., val is : 93
c2 ----consume done..., val is : 83
c1 ----consume done..., val is : 77
p1 ---product done..., val is : 49
p2 ---product done..., val is : 62
c2 ----consume done..., val is : 93
c2 ----consume done..., val is : 49
c1 ----consume done..., val is : 62
p1 ---product done..., val is : 26
p1 ---product done..., val is : 26
p1 ---product done..., val is : 36
p2 ---product done..., val is : 68
p1 ---product done..., val is : 29
c1 ----consume done..., val is : 26
c1 ----consume done..., val is : 26
p1 ---product done..., val is : 23
p2 ---product done..., val is : 35
c2 ----consume done..., val is : 36
p1 ---product done..., val is : 22
^C
process done ...

读写者关系:

读者-读者  (共享 即 没关系)

读者-写者 (同步)

写者-写者 (互斥)

在编写多线程的时候,有一种情况是十分常见的。那就是,有些公共数据修改的机会比

较少。相比较改写,它们读的机会反而高的多。通常而言,在读的过程中,往往伴随着查

找的操作,中间耗时很长。给这种代码段加锁,会极大地降低我们程序的效率。那么有没

有一种方法,可以专门处理这种多读少写的情况呢?

有,那就是读写锁。

读写锁实际是一种特殊的自旋锁,它把对共享资源的访问者划分成读者和写者,读者只

对共享资源进行读访问,写者则需要对共享资源进行写操作。这种锁相对于自旋锁而言,

能提高并发性,因为在多处理器系统中,它允许同时有多个读者来访问共享资源,最大可

能的读者数为实际的逻辑 CPU数。写者是排他性的,一个读写锁同时只能有一个写者或多

个读者(与 CPU数相关),但不能同时既有读者又有写者。


通常, 当读写锁处于读模式锁住状态时, 如果有另外线程试图以写模式加锁, 读写锁通常会阻塞随后的读模式锁请求, 这样可以避免读模式锁长期占用, 而等待的写模式锁请求长期阻塞.


读写锁适合于对数据结构读次数比写次数多得多的情况. 因为, 读模式锁定时可以共享, 以写模式锁住时意味着独占, 所以读写锁又叫共享-独占锁.


用到的函数:

      

 int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
       int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);
       int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
       int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
       int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
       int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);

练习代码:

#include<stdio.h>
#include <pthread.h>
#define _READER_NUM_ 3
#define _WRITER_NUM_ 2
pthread_rwlock_t lock;
int buf = 0;
void *read(void* _val)
{
    pthread_detach(pthread_self());
    while (1)
    {
        if (pthread_rwlock_tryrdlock(&lock) != 0)
        {
            printf("writer is writing, reader waiting...\n");
        }
        else
        {
            printf("reader is : %u, read val is : %d,\n", pthread_self(), buf);
            pthread_rwlock_unlock(&lock);
        }
        sleep(2);
    }
}
void * write(void* _val)
{
    pthread_detach(pthread_self());
    while (1)
    {
        if (pthread_rwlock_trywrlock(&lock) != 0)
        {
            printf("reader is reading, writer waiting...\n");
            sleep(1);
        }
        else
        {
            buf++;
            printf("writer is %u : write val is : %d\n", pthread_self(), buf);
            pthread_rwlock_unlock(&lock);
        }
        sleep(1);
    }
}
int main()
{
    pthread_rwlock_init(&lock, NULL);
    pthread_t id;
    int i;
    for (i = 0; i < _WRITER_NUM_; i++)
    {
        pthread_create(&id, NULL, write , NULL);
    }
    for (i = 0; i < _READER_NUM_; i++)
    {
        pthread_create(&id, NULL, read, NULL);
    }
    sleep(100);
    return 0;
}

运行:

[bozi@localhost test_20160730]$ gcc -o reader_writer reader_writer.c -pthread
[bozi@localhost test_20160730]$ ./reader_writer
reader is : 3046312816, read val is : 0,
reader is : 3035822960, read val is : 0,
reader is : 3056802672, read val is : 0,
writer is 3067292528 : write val is : 1
writer is 3077782384 : write val is : 2
writer is 3067292528 : write val is : 3
writer is 3077782384 : write val is : 4
reader is : 3046312816, read val is : 4,
reader is : 3035822960, read val is : 4,
reader is : 3056802672, read val is : 4,
writer is 3067292528 : write val is : 5
writer is 3077782384 : write val is : 6
writer is 3067292528 : write val is : 7
writer is 3077782384 : write val is : 8
reader is : 3046312816, read val is : 8,
reader is : 3035822960, read val is : 8,
reader is : 3056802672, read val is : 8,
writer is 3067292528 : write val is : 9
writer is 3077782384 : write val is : 10


1、什么是死锁

     如果一组进程中,每一个进程否在等待仅由改组进程中的其他进程才能引发的事件,那么改组进程是死锁的。

2、死锁的产生条件

4个必要条件:

     1) 互斥条件:一段时间内,某资源只能被一个进程占用。

     2)请求和保持条件: 进程自己手里已经占有资源,还想申请别的资源,因别的资源申请不到而阻塞,但还不释放自己手上的资源。

    3) 不可抢占条件:进程已经获得的资源在没有使用完之前不能被抢占,只能在进程使用完时自己释放。

     4)循环等待条件:p0等p1的资源,p1等p2的资源,...pn等p0的资源,形成一个 进程-资源 循环链

3、如何避免死锁

方法一:事先采取某种限制措施,如破环产生死锁的必要条件

因为互斥条件是非共享设备所必须的,不仅不能改变,还应加以保护,因此,主要是破坏产生死锁的后三个条件。

1)破坏“2请求和保持条件”:方法一:进程必须一次性申请完自己运行时所需要的所有资源,即要么全申请,要么一个也不申请。

                                              方法二:允许一个进程只获得运行初期所需要的资源,运行中再释放已经用完的全部资源,然后申请新的资源。这比方法一好,

                                                           可以减少进程发生饥饿的几率。

2)破坏“3不可抢占条件”条件:进程申请不到新的资源,必须先把自己已经获得的资源释放,换句话说就是自己手里已经有的资源被抢占了 这样就破坏了不可                          

                                                  抢占条件。

3)破坏“4循环等待”条件 : 对资源编号,进程每次申请多个资源时,由低到高申请 ,如果需要多个同类资源必须一起申请,如果申请序号低的资源,必须释         

                                             放手上比这个信号高或者相等的资源后,才能申请序号低的资源。

方法二:

               在资源分配过程中,防止系统进入不安全状态。系统分配资源之前,先计算一下分配好系统是否还安全,然后再决定此次进程的请求是否可行。

               著名算法:银行家算法

                    

互斥锁 完成 互斥

条件变量  完成 同步



本文出自 “城市猎人” 博客,请务必保留此出处http://alick.blog.51cto.com/10786574/1832251

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值