pthread使用的例子程序以及内存泄露问题

        使用pthread需要注意的是调用pthread_create函数创建线程之后,记得要在线程函数中最后调用pthread_exit函数退出。否则会造成内存泄露,下面是例子,引用自:http://www.amparo.net/ce155/thread-ex.html


/* Includes */
#include <unistd.h>     /* Symbolic Constants */
#include <sys/types.h>  /* Primitive System Data Types */
#include <errno.h>      /* Errors */
#include <stdio.h>      /* Input/Output */
#include <stdlib.h>     /* General Utilities */
#include <pthread.h>    /* POSIX Threads */
#include <string.h>     /* String handling */

/* prototype for thread routine */
void print_message_function ( void *ptr );

/* struct to hold data to be passed to a thread
   this shows how multiple data items can be passed to a thread */
typedef struct str_thdata
{
    int thread_no;
    char message[100];
} thdata;

int main()
{
    pthread_t thread1, thread2;  /* thread variables */
    thdata data1, data2;         /* structs to be passed to threads */
   
    /* initialize data to pass to thread 1 */
    data1.thread_no = 1;
    strcpy(data1.message, "Hello!");

    /* initialize data to pass to thread 2 */
    data2.thread_no = 2;
    strcpy(data2.message, "Hi!");
   
    /* create threads 1 and 2 */   
    pthread_create (&thread1, NULL, (void *) &print_message_function, (void *) &data1);
    pthread_create (&thread2, NULL, (void *) &print_message_function, (void *) &data2);

    /* Main block now waits for both threads to terminate, before it exits
       If main block exits, both threads exit, even if the threads have not
       finished their work */
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
             
    /* exit */ 
    exit(0);
} /* main() */

/**
* print_message_function is used as the start routine for the threads used
* it accepts a void pointer
**/
void print_message_function ( void *ptr )
{
    thdata *data;           
    data = (thdata *) ptr;  /* type cast to a pointer to thdata */
   
    /* do the work */
    printf("Thread %d says %s /n", data->thread_no, data->message);
   
    pthread_exit(0); /* exit */
} /* print_message_function ( void *ptr ) */

 

后记:
      好像我搞错了,要防止内存泄露需要在主线程中执行pthread_join. 我加了pthread_exit还是会提示泄露。起始也容易明白,pthread_join是等待子线程结束,并且堵塞主线程,如果没有的话,主线程直接结束,子线程可能还没结束,因此主线程退出时内存并没有完全释放。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值