线程的编程

完整代码 

#include <sys/shm.h>
#include <iostream>
#include <unistd.h>
#include <pthread.h>void * child1(void *arg){pthread_t tid = pthread_self();printf("1 thread %lu \n",tid);}int main(int argc,char* argv[]) {int result{};pthread_t a_thread{};pthread_t tid = pthread_self();printf("mean thread %lu \n",tid);result = pthread_create(&a_thread, nullptr,child1, nullptr);if (result !=0){printf("Thread create failed!");}return 0;
}

  • 如果主线程 不延时,直接退出,子线程还未创建就结束了

线程终止

  • pthread_join()    等待线程退出,第二个参数是线程退出返回的数值
#include <sys/shm.h>
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <cstring>void * child1(void *arg){pthread_t tid = pthread_self();printf("1 thread %lu \n",tid);}void * thread_function(void *arg);int main(int argc,char* argv[]) {int result{};std::string message{"Hello World"};pthread_t a_thread{};pthread_t tid = pthread_self();printf("mean thread %lu \n",tid);result = pthread_create(&a_thread, nullptr,thread_function, (void *)(message.c_str()));if (result !=0){printf("Thread create failed!");exit(EXIT_FAILURE);}printf("Waiting for thread to finish!\n");void * thread_result;result = pthread_join(a_thread,&thread_result);if (result !=0){printf("Thread join failed!");exit(EXIT_FAILURE);}printf("Thread joined,it returned %s\n",(char *)thread_result);printf("Message is now %s \n",message.c_str());exit(EXIT_SUCCESS);return 0;
}void * thread_function(void *arg){char * message = (char *)arg;printf("thread_function is running.Argument was %s\n",message);sleep(3);strcpy(message,"Bye!");pthread_exit((void *) "Thank you for the cpu time!");
}

  • 多线程 全局变量  共享;注意同步 和 互斥

代码 生产者 消费者模型

#include <sys/shm.h>
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <cstring>#define BUFFER_SIZE 16
#define OVER -1struct prodcons {int buffer[BUFFER_SIZE];//设置缓冲区数组pthread_mutex_t lock;//互斥锁int read_pos,write_pos;//读写位置pthread_cond_t not_empty;//缓冲区非空信号pthread_cond_t not_full;//缓冲区非满信号
};struct prodcons buffer;void init(struct prodcons *b){pthread_mutex_init(&b->lock, nullptr);pthread_cond_init(&b->not_empty, nullptr);pthread_cond_init(&b->not_full, nullptr);b->read_pos = 0;b->write_pos = 0;
}void put(struct prodcons *b,int data){pthread_mutex_lock(&b->lock);//等待缓冲区非满while ((b->write_pos + 1) % BUFFER_SIZE == b->read_pos ){printf("wait for not full!\n");pthread_cond_wait(&b->not_full,&b->lock);}//写数据并且指针前移b->buffer[b->write_pos] = data;b->write_pos++;if (b->write_pos >= BUFFER_SIZE)b->write_pos = 0;//设置缓冲区非空的信号pthread_cond_signal(&b->not_empty);pthread_mutex_unlock(&b->lock);
}int get(struct prodcons *b){int data;pthread_mutex_lock(&b->lock);//等待缓冲区非空while (b->write_pos == b->read_pos){printf("wait for not empty!");pthread_cond_wait(&b->not_empty,&b->lock);}//读数据并且指针前移data = b->buffer[b->read_pos];b->read_pos++;if (b->read_pos >= BUFFER_SIZE)b->read_pos = 0;//设置缓冲区非满的信号pthread_cond_signal(&b->not_full);pthread_mutex_unlock(&b->lock);return data;
}void * producer(void *data){for (int i = 0; i < 10; ++i) {printf("put --> %d\n",i);put(&buffer,i);}put(&buffer,OVER);printf("producer stopped!\n");return nullptr;
}void * consumer(void *data){int d{};while (1){d = get(&buffer);if (d == OVER)break;printf("%d->get\n",d);}printf("consumer stopped!");return nullptr;
}int main(int argc,char* argv[]) {pthread_t th_a{},th_b{};void *ret_val;struct prodcons x{};init(&x);pthread_create(&th_a, nullptr, reinterpret_cast<void *(*)(void *)>(producer), 0);pthread_create(&th_b, nullptr,reinterpret_cast<void *(*)(void *)>(consumer), 0);//等待生产者和消费者结束pthread_join(th_a,&ret_val);pthread_join(th_b,&ret_val);return 0;
}

参考链接

  • 线程相关函数(2)-pthread_self()获取调用线程ID
  • pthread_join的使用
  • pthread_cond_wait()用法分析

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/446623.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

英语口语 week11 Friday

英语文章 I very much like simplicity in life. For me, college is far more than a place to improve my intellectual abilities Every weekend, I usually have a walk along the way to the front gate of Mount Qingcheng, enjoying the intense aromas of flowers on …

c++面向对象高级编程 学习五 组合、委托与继承

组合 composition 表示has a queue类中有一个deque容器&#xff0c;这种关系叫做 组合 queue中的六个函数都是调用c的函数完成的 template <class T> class queue { ... protected: deque<T> c; // 底層容器 public: // 以下完全利用 c 的操作函數完成 bool empt…

英语口语 week12 WednesDay

英语文章 Chengdu, a city with a long history, has always enjoyed the reputation as " The Land of Abundance" . It has been noted as one of the most livable cities in China, partly resulting from its favorable natural conditions and wealthy produc…

c++面向对象高级编程 学习六 虚函数

虚函数&#xff1a;在成员函数前面加上virtual&#xff0c;函数就变成了虚函数 继承函数&#xff1a;子类可以调用父类的函数&#xff0c;叫做继承了函数&#xff0c;即函数的调用权 三种函数&#xff1a; non-virtual 函数&#xff1a; 你不希望 derived class 重新定义 (ov…

C++ 数据结构 线性链表

#pragma once 减少头文件组合&#xff0c;降低编译出错的概率作用等效于 #ifndef FUNC_H #define FUNC_H代码主体#endif 线性表的定义 排队问题 简单的线性表 (物理 或者逻辑结构)1&#xff0c;数组2&#xff0c;链表线性表相关操作&#xff1a;1&#xff0c;线性表初始化2&a…

英语口语 week12 Thursday

英语文章 As the pace of life quickens with technological advancements, people are occupied by all kinds of trivial matters. They seem forever on the go. There’s no difficulty in imagining that the hustle and bustle of everyday life can make us lose focus…

H.264/AVC视频编解码技术详解 第一章 视频信息与压缩编码

H.264/AVC视频编解码技术详解系列笔记 是对 H.264/AVC视频编解码技术详解 课程的学习 文章目录人与世界的交互视频信号的表示方法视频压缩编码视频信息为什么可以被压缩&#xff1f;视频压缩编码的分类&#xff1a;视频压缩编码的基本技术人与世界的交互 从远古时代开始&#…

英语口语 week13 Monday

英语文章 Competitions between businesses can be very aggressive in contemporary society. However, the competition for talented personnel is thought to be the key to business competition. Wise employers consider their employees as the company’s core asset…

文件系统的由来

启蒙篇 文件的由来 磁盘上保存的是一对十六进制的数据&#xff0c;如何切分数据形成不同的文件&#xff0c;也就是如何确定一个文件的起始和终止位置&#xff1f;将相关数据打包在一起形成一个文件&#xff0c;比如从什么位置开始到什么位置结束&#xff0c;是一张图片、一段…

英语口语 week13 Wednesday

英语文章 Despite his extraordinary success in writing fairy tales,Hans Christian Andersen preferred to living in a way of simplicity and frugality. He often wore an old hat when he went out. One day, a well-dressed man stopped Andersen on the street, inte…

操作系统 IO管理

学什么&#xff1f; I/O input / output 输入&#xff1a;鼠标 键盘 手柄 触摸屏 摄像头 MTC 扫描仪输出&#xff1a;显示器 打印机 耳机 音响 既是输入也是输出&#xff1a;光驱 网卡 磁盘 U盘硬件&#xff1a;设备如何把数据返回到PC机&#xff0c;但是不同种类的设…

c++面向对象高级编程 学习九 pointer-like classes

c的class设计出来有两种形式&#xff0c;一种像指针&#xff0c;一种像函数 智能指针里包含普通指针&#xff0c;要写 * 和 -> 的函数 sp->method(); //sp-> 经 T* operator*() const 函数&#xff0c;得到px //由于 箭头符号&#xff08;->&#xff09;作用下去…

const int *a和int*const a 的区别详解

补充知识 “const int i”与“int const i”之间的区别对变量来说&#xff0c;const 关键字可以限定一个变量的值不允许改变&#xff0c;从而保护被修饰的东西&#xff0c;防止意外修改&#xff0c;在一定程度上可以提高程序的安全性和可靠性。 代码 const int * int i1 10…

c++面向对象高级编程 学习十 function-like classes

本节是设计一个class&#xff0c;使它的行为像一个函数。 如果一个东西能接受小括号()操作符&#xff0c;那么这个东西就称之为函数&#xff0c;或像函数的东西。 下图为三个函数对()的重载&#xff0c;这三个类均为像函数的类&#xff0c;它们可接受()操作符&#xff0c; 标…

英语口语 Week14 Monday

英语文章 Thailand, a country in Southeast Asia with an area of about 514,000 square kilometers, has been increasingly prosperous in its tourism industry in the past few decades. Its capital is Bangkok and its major languages are Thai, Chinese and English.…

c++面向对象高级编程 学习十一 类模板、函数模板、成员模板

namespace经验谈&#xff1a; 团队中函数或类的名字可能会冲突&#xff0c;因此使用namespace进行区分。 类模板&#xff1a; template<typename T> 函数模板&#xff1a; template<class T>&#xff0c;此处class可改成typename 函数模板在使用的时候&#xff0…

操作系统面试 总结

以下文章来源于程序员cxuan &#xff0c;作者cxuan 原文链接什么是操作系统 操作系统是管理硬件和软件的一种应用程序。操作系统是运行在计算机上最重要的一种软件&#xff0c;它管理计算机的资源和进程以及所有的硬件和软件。它为计算机硬件和软件提供了一种中间层&#xff…

英语口语week 14 Thursday

英语文章 A couple decided to go out to celebrate their wedding anniversary, so they called a babysitter. When the babysitter arrived, the two children had already been asleep. The babysitter soon got bored and went to the kitchen where she blended some wh…

c++面向对象高级编程 学习十二 模板

模板特化&#xff1a; 模板是一种泛化的形式&#xff0c;特化是将参数类型进行指定&#xff0c;写出特化的版本&#xff0c;当在调用下图cout<<hash()(1000);的时候&#xff0c;由于特化中有struct hash{ }的版本&#xff0c;因此会直接调用特化部分。 模板偏特化&…

英语口语 week14 Friday

英语文章 Shopping is taking place every second. However, the prices of the same goods may differ from store to store. A name-brand dress may cost several hundred pounds at a boutique, but only half the price in a discount store or a big chain store. Moreo…