Chinaunix首页 | 论坛 | 博客
  • 博客访问: 640695
  • 博文数量: 128
  • 博客积分: 4385
  • 博客等级: 上校
  • 技术积分: 1546
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-22 14:05
文章分类

全部博文(128)

文章存档

2012年(2)

2011年(51)

2010年(75)

分类: LINUX

2010-08-26 16:12:34

多线程实验
1.创建线程  定义线程函数  保护线程,退出时清除资源   定义清除函数
2.当主进程中用pthread_join时,先执行线程,主进程等待相应线程执行结束,再执行。
  否则,先执行主进程,主进程中若sleep,则执行线程,否则主进程直接执行结束。
 
 

#include <pthread.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int a = 1;

void *clean(void *arg)
{
    printf("cleanup :%s\n", (char *)arg);    //change the type of arg

    return (void *)0;    //the type of return is *p

}
void *pth1 (void *arg)
{
    pthread_cleanup_push((void *)clean, "thread 1"); //resource recovery

    int *num;
    num = (int *)arg;    //change the type of parametre

    a++;
    printf("pthread:a = %d\n", a);
    printf("the num=%d\n", *num);
    pthread_exit((void *)1);
    pthread_cleanup_pop(0); //resource recovery when exit

    return (void *)0;
}

main(void)
{
    int num = 4;
    pthread_t tidp;
    a++;
    int *arg = &num;    //change the type of parametre

    if(pthread_create(&tidp, NULL,(void *)pth1,(void *)arg) < 0)
    {
        printf("create error:%s\n", strerror(errno));
        exit(1);
    }
    pthread_join(tidp,NULL);
    printf("main:a = %d\n", a);
//    sleep(1);

    printf("this is process!\n");
}

易错点:

1.pthread_create 函数中参数的类型

2.void *pth1 (void *arg) 线程函数为返回值为指针的函数

阅读(1346) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~