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
原创粉丝点击