18.pthread POSIX线程

简介: (创建于 2018/3/1 上午7:11:44)查看pthread所有方法man -k pthread输出结果pthread_attr_destroy (3) - initialize and destroy thread attribute...

(创建于 2018/3/1 上午7:11:44)

查看pthread所有方法

man -k pthread

输出结果

pthread_attr_destroy (3) - initialize and destroy thread attributes object
pthread_attr_getaffinity_np (3) - set/get CPU affinity attribute in thread attributes object
pthread_attr_getdetachstate (3) - set/get detach state attribute in thread attributes object
pthread_attr_getguardsize (3) - set/get guard size attribute in thread attributes object
pthread_attr_getinheritsched (3) - set/get inherit-scheduler attribute in thread attribute...
pthread_attr_getschedparam (3) - set/get scheduling parameter attributes in thread attribu...
pthread_attr_getschedpolicy (3) - set/get scheduling policy attribute in thread attributes...
pthread_attr_getscope (3) - set/get contention scope attribute in thread attributes object
pthread_attr_getstack (3) - set/get stack attributes in thread attributes object
pthread_attr_getstackaddr (3) - set/get stack address attribute in thread attributes object
pthread_attr_getstacksize (3) - set/get stack size attribute in thread attributes object
pthread_attr_init (3) - initialize and destroy thread attributes object
pthread_attr_setaffinity_np (3) - set/get CPU affinity attribute in thread attributes object
pthread_attr_setdetachstate (3) - set/get detach state attribute in thread attributes object
pthread_attr_setguardsize (3) - set/get guard size attribute in thread attributes object
pthread_attr_setinheritsched (3) - set/get inherit-scheduler attribute in thread attribute...
pthread_attr_setschedparam (3) - set/get scheduling parameter attributes in thread attribu...
pthread_attr_setschedpolicy (3) - set/get scheduling policy attribute in thread attributes...
pthread_attr_setscope (3) - set/get contention scope attribute in thread attributes object
pthread_attr_setstack (3) - set/get stack attributes in thread attributes object
pthread_attr_setstackaddr (3) - set/get stack address attribute in thread attributes object
pthread_attr_setstacksize (3) - set/get stack size attribute in thread attributes object
pthread_cancel (3)   - send a cancellation request to a thread
pthread_cleanup_pop (3) - push and pop thread cancellation clean-up handlers
pthread_cleanup_pop_restore_np (3) - push and pop thread cancellation clean-up handlers wh...
pthread_cleanup_push (3) - push and pop thread cancellation clean-up handlers
pthread_cleanup_push_defer_np (3) - push and pop thread cancellation clean-up handlers whi...
pthread_create (3)   - create a new thread
pthread_detach (3)   - detach a thread
pthread_equal (3)    - compare thread IDs
pthread_exit (3)     - terminate calling thread
pthread_getaffinity_np (3) - set/get CPU affinity of a thread
pthread_getattr_np (3) - get attributes of created thread
pthread_getconcurrency (3) - set/get the concurrency level
pthread_getcpuclockid (3) - retrieve ID of a thread's CPU time clock
pthread_getname_np (3) - set/get the name of a thread
pthread_getschedparam (3) - set/get scheduling policy and parameters of a thread
pthread_join (3)     - join with a terminated thread
pthread_kill (3)     - send a signal to a thread
pthread_kill_other_threads_np (3) - terminate all other threads in process
pthread_rwlockattr_getkind_np (3) - set/get the read-write lock kind of the thread read-wr...
pthread_rwlockattr_setkind_np (3) - set/get the read-write lock kind of the thread read-wr...
pthread_self (3)     - obtain ID of the calling thread
pthread_setaffinity_np (3) - set/get CPU affinity of a thread
pthread_setcancelstate (3) - set cancelability state and type
pthread_setcanceltype (3) - set cancelability state and type
pthread_setconcurrency (3) - set/get the concurrency level
pthread_setname_np (3) - set/get the name of a thread
pthread_setschedparam (3) - set/get scheduling policy and parameters of a thread
pthread_setschedprio (3) - set scheduling priority of a thread
pthread_sigmask (3)  - examine and change mask of blocked signals
pthread_sigqueue (3) - queue a signal and data to a thread
pthread_testcancel (3) - request delivery of any pending cancellation request
pthread_timedjoin_np (3) - try to join with a terminated thread
pthread_tryjoin_np (3) - try to join with a terminated thread
pthread_yield (3)    - yield the processor
pthreads (7)         - POSIX threads
root@iZbp11v3y27wpf6mglp2glZ:/user/renzhenming/pthread# 

1.线程创建与退出

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

void* thr_fun(void* arg){
    char* no = (char*)arg;
    int i = 0;
    for(; i < 10; i++){
        printf("%s thread, i:%d\n",no,i);
        if(i==5){
            //线程退出(自杀)
            pthread_exit(2);
            //他杀pthread_cancel          
        }
    }   
    return 1;
}

void main(){
    printf("main thread\n");
    //线程id
    pthread_t tid;
    //线程的属性,NULL默认属性
    //thr_fun,线程创建之后执行的函数
    pthread_create(&tid,NULL,thr_fun,"1");
    void* rval;
    //等待tid线程结束
    //thr_fun与退出时传入的参数,都作为第二个参数的内容
    pthread_join(tid,&rval);
    printf("rval:%d\n",(int)rval);
}

2.互斥锁

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

int i = 0;
//互斥锁
pthread_mutex_t mutex;

void* thr_fun(void* arg){
    //加锁
    pthread_mutex_lock(&mutex);
    char* no = (char*)arg;
    for(;i < 5; i++){
        printf("%s thread, i:%d\n",no,i);
        sleep(1);
    }
    i=0;
    //解锁
    pthread_mutex_unlock(&mutex);
}

void main(){
    pthread_t tid1, tid2;
    //初始化互斥锁
    pthread_mutex_init(&mutex,NULL);

    pthread_create(&tid1,NULL,thr_fun,"No1");
    pthread_create(&tid2,NULL,thr_fun,"No2");

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);

    //销毁互斥锁
    pthread_mutex_destroy(&mutex);
}

3.线程唤醒与等待

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

//消费者数量
#define CONSUMER_NUM 2
//生产者数量
#define PRODUCER_NUM 1

pthread_t pids[CONSUMER_NUM+PRODUCER_NUM];

//产品队列
int ready = 0;

//互斥锁
pthread_mutex_t mutex;
//条件变量
pthread_cond_t has_product;

//生产
void* producer(void* arg){
    int no = (int)arg;
    //条件变量
    for(;;){
        pthread_mutex_lock(&mutex);
        //往队列中添加产品
        ready++;
        printf("producer %d, produce product\n",no);
        //fflush(NULL);
        //通知消费者,有新的产品可以消费了
        //pthread_cond_signal会阻塞输出,假设发出信号后没有接收信号的线程,
        //会导致上边一行的打印不会出现,被它阻塞了,输出还在缓冲区中没有打印出来,刷新缓冲区fflush后可以显示
        pthread_cond_signal(&has_product);
        printf("producer %d, singal\n",no);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}

//消费者
void* consumer(void* arg){
    int num = (int)arg;
    for(;;){
        pthread_mutex_lock(&mutex);
        //while?(为什么不用if)
        //superious wake ‘惊群效应’
        //因为线程被唤醒的条件不只时我们发送signal,还有一个经群效应导致的线程唤醒,如果用if,会导致这种情况下的问题,用while可以持续的判断条件ready==0,避免这种情况
        while(ready==0){
            //没有产品,继续等待
            //1.阻塞等待has_product被唤醒
            //2.释放互斥锁,pthread_mutex_unlock
            //3.被唤醒时,解除阻塞,重新申请获得互斥锁pthread_mutex_lock
            printf("%d consumer wait\n",num);
            pthread_cond_wait(&has_product,&mutex);
        }
        //有产品,消费产品
        ready--;
        printf("%d consume product\n",num);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}


void main(){
    //初始化互斥锁和条件变量                                                
    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&has_product,NULL);
    printf("init\n");

    int i;
    for(i=0; i<PRODUCER_NUM;i++){
        //生产者线程
        printf("%d\n",i);
        pthread_create(&pids[i],NULL,producer,(void*)i);
    }
    
    for(i=0; i<CONSUMER_NUM;i++){
        //消费者线程
        pthread_create(&pids[PRODUCER_NUM+i],NULL,consumer,(void*)i);
    }
    
    //等待
    sleep(10);
    for(i=0; i<PRODUCER_NUM+CONSUMER_NUM;i++){
        pthread_join(pids[i],NULL);
    }
    
    //销毁互斥锁和条件变量
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&has_product);
    
}


//while?(为什么不用if)


img_0bec203aeae27360e7f78ccfc7a3496b.png
184036781.png
相关文章
|
16天前
|
Linux C++
LInux下Posix的传统线程示例
LInux下Posix的传统线程示例
15 1
|
3月前
|
Unix API 调度
POSIX线程基本操作
POSIX线程基本操作
34 0
|
3月前
|
数据挖掘 API 数据处理
POSIX线程私有空间
POSIX线程私有空间
22 0
|
7月前
|
存储 安全 Linux
Posix多线程编程
Posix多线程编程
45 0
Pthread线程使用详解
文中先讲解函数,再运行实例,以及一些注意事项
156 0
|
Linux
Linux系统编程-(pthread)线程通信(读写锁)
**读写锁与互斥锁类似,读写锁比互斥锁有更高的并行性,读写锁特点如下:** ​ 1. 读写锁有三种状态,读模式下加锁(共享)、写模式下加锁(独占)以及不加锁。 ​ 2. 一次只有一个线程可以占有写模式下的读写锁;但是多个线程可以同时占有读模式下的读写锁。 ​ 3. 读写锁在写加锁状态时,其他试图以写状态加锁的线程都会被阻塞。读写锁在读加锁状态时,如果有线程希望以写模式加锁时,必须阻塞,直到所有线程释放锁。 ​ 4. 当读写锁以读模式加锁时,如果有线程试图以写模式对其加锁,那么读写锁会阻塞随后的读模式锁请求,以避免读锁长期占用,而写锁得不到请求。
190 0
|
Linux
Linux系统编程-(pthread)线程的使用案例(分离属性、清理函数等)
这篇文章介绍Linux下线程的创建与基本使用案例,主要是案例代码为主;相关的函数详细介绍在上篇文章里已经介绍过了。
189 0
|
存储 消息中间件 Unix
Linux系统编程-(pthread)线程创建与使用
前面文章介绍了Linux下进程的创建、管理、使用、通信,了解了多进程并发;这篇文章介绍Linux下线程的基本使用。
267 0
|
Linux
Linux Qt使用POSIX多线程条件变量、互斥锁(量)
Linux Qt使用POSIX多线程条件变量、互斥锁(量)今天团建,但是文章也要写。酒要喝好,文要写美,方为我辈程序员的全才之路。嘎嘎 之前一直在看POSIX的多线程编程,上个周末结合自己的理解,写了一个基于Qt的用条件变量同步线程的例子。
1342 0
|
Java Android开发 开发工具
20.Eclipse下Ndk开发(pthread开启线程调用Java方法)
本项目最终的目的是在pthread线程中,调用Java一个工具类得到多个uuid,然后调用类中另一个方法弹出toast,实现在c中获取安卓上下文对象Context 编译native方法,生成头文件的一系列过程不再赘述,直接上代码,都在注释中 PosixUtils: package com.
1206 0

热门文章

最新文章