pthread 编程中的传参以及栈中变量的生存周期
来源:互联网 发布:淘宝追加评价有信誉吗 编辑:程序博客网 时间:2024/04/28 13:18
demo代码如下:
#include <stdio.h>
#include <string.h>#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX1 10
#define MAX2 30
pthread_t thread[2];
int number=0, i;
void *thread1(void* arg1)
{
sleep(3);
printf ("thread1 : I'm thread 1 ,arg1:%d \n", (arg1));
pthread_exit(NULL);
}
void *thread2(void* arg)
{
printf("thread2 : I'm thread 2 , arg2:%d \n", arg);
pthread_exit(NULL);
}
void thread_create(void)
{
int temp;
memset(&thread, 0, sizeof(thread)); //comment1
int arg1 = 1;
/*创建线程*/
if((temp = pthread_create(&thread[0], NULL, thread1, (void*)arg1) != 0))
printf("线程1创建失败!\n");
else
printf("Thread 1 is established\n");
arg1++;
printf("++\n");
if((temp = pthread_create(&thread[1], NULL, thread2, (void*)arg1)) != 0) //comment3
printf("线程2创建失败");
else
printf("Thread 2 is established\n");
}
void thread_wait(void)
{
/*等待线程结束*/
if(thread[0] !=0) { //comment4
pthread_join(thread[0],NULL);
printf("Thread 1 is over \n");
}
printf("-----------------------------------------\n");
if(thread[1] !=0) { //comment5
pthread_join(thread[1],NULL);
printf("Thread 2 is over\n");
}
}
int main()
{
printf("I am the main funtion,and I am establishing threads. Ha-ha\n");
thread_create();
printf("I am the main funtion,and I am waiting for thread to accomplish task. Ha-ha\n");
thread_wait();
return 0;
}
1.传参
线程函数为 void* fun(void* arg),返回值和给进参数均void* ,且参数为一个;
int a; pthread_create函数创建的时候,(void*)a的形式给进去,在线程函数中的arg则为a,可以直接进行使用,若为指针类型,则线程函数中的arg即为
指针,进行相应转换后便可使用。(有些废话,不过按照此规则可以避免很多调试弯路)
2.栈中变量
如上demo代码中arg1变量,thread_create函数结束推出后,并不会影响后续子线程的调研,子线程栈中的参数变量是在创建的时候给进,并不会因原有变量的销毁
而产生错误。
3. 等待
pthread_join函数执行时,阻塞等待,直到线程结束。
4. 以上所有结论,纯属扯淡,一家之谈,自己备忘,客观莫要全信。
擦 ==!
0 0
- pthread 编程中的传参以及栈中变量的生存周期
- C++中变量的生存周期
- java语言基础-学习笔记-java中变量的本质、分类、存储以及生存周期
- SESSION变量的生存周期
- php中 常量,变量的作用域和生存周期
- struts2 action中成员变量的生存周期
- c++循环语句中变量的生存周期
- for循环局部变量的生存周期
- js变量的作用域详解、生存周期,以及一些小细节。
- 生存周期小的变量优先权大于生存周期大的变量
- auto变量在for循环中的生存周期
- 静态变量,静态局部变量的生存周期
- 生存周期中的指针
- 2、C语言中变量的存储,生存周期,作用范围分类
- C++中对象的生存周期
- 如何将session数据保存到memcache中,以及memcache的生存周期
- 如何将session数据保存到memcache中,以及memcache的生存周期
- C++变量生存周期演示
- Android快捷方式解密
- Android应用程序永久获取root权限方法
- android微信分享到朋友圈 图片过大闪退
- VS2010创建和使用COM组件
- Android设置Settings实现:PreferenceActivity
- pthread 编程中的传参以及栈中变量的生存周期
- 测试CSRF
- Centos下python安装 MySQLdb报错
- Android出现Immutable bitmap passed to Canvas constructor错误的原因
- IntentService源码分析
- 基于egret引擎、P2物理库的搭积木游戏
- JS 获取鼠标所点击表格中的某行某列的值
- 红黑树(四)之 C++的实现 http://www.cnblogs.com/skywang12345/p/3624291.html?utm_source=tuicool&utm_medium=refe
- java操作sql server数据中,关于PreparedStatement数据注入问题