|
Linux之Ubuntu c++多线程代码demo
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <pthread.h>
- void * Thread_collect(void *args){
- //拿到主线程传过来的参数
- int *counter_p = (int *)args;
- for(int i=0; i<5; i++){
- *counter_p = *counter_p + 2;
- printf("收集数据线程。。。%d\n", *counter_p);
- sleep(1);
- }
- return NULL;
- }
- void * Thread_process(void *args){
- int *counter_p = (int *)args;
- for(int i=0; i<6; i++){
- *counter_p = *counter_p + 1;
- printf("算法处理线程。。。%d\n", *counter_p);
- sleep(1);
- }
- return NULL;
- }
- int main(){
- //Linux之Ubuntu c++多线程代码demo
- //g++ -g -o dm dm03_雷达实时多线程.cpp -lpthread
- // ./dm执行即可
- //主线程:创建公共队列、维护队列、最后清空和销毁队列 创建2个子线程并维护他们的回调
- //子线程1:从usb口源源不断的实时取数据 并放队列里面
- //子线程2:从队里里拿数据 做实时信号算法处理
- int counter_common = 10;
- printf("雷达实时算法入口【Linux系统】...主线程初始计数器=%d\n", counter_common);
- //两个线程去操作 计数器 指针
- pthread_t handle_collect, handle_process;
- int err1 = pthread_create(&handle_collect,NULL,Thread_collect,&counter_common);
- int err2 = pthread_create(&handle_process,NULL,Thread_process,&counter_common);
- if(err1 == 0 && err2 == 0){
- printf("主线程:创建2个子线程成功!\n");
- }
- //主线程要等到创建的线程返回了,获取该线程的返回值后主线程才退出
- // 只等待子线程,但是不关心子线程的退出值
- pthread_join(handle_collect, NULL);
- pthread_join(handle_process, NULL);
- printf("等所有子线程执行完毕.。。再回到主线程,再看计数器=%d\n", counter_common);
- return 0;
- }
复制代码
|
|