Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1265618
  • 博文数量: 264
  • 博客积分: 10772
  • 博客等级: 上将
  • 技术积分: 2325
  • 用 户 组: 普通用户
  • 注册时间: 2007-07-25 11:54
文章分类

全部博文(264)

文章存档

2012年(4)

2011年(51)

2010年(31)

2009年(57)

2008年(51)

2007年(70)

分类: LINUX

2009-11-05 17:37:15

#include <pthread.h>
#include <stdio.h>
#include <sys/time.h>
#include <string.h>
#define MAX 10
#define MAXTHREAD 100
pthread_t thread[MAXTHREAD];
pthread_mutex_t mut;
int number=0;

typedef struct
{
    int a;
}countStruct;

void *thread1(void *threadcount)
{
    countStruct *tc;
    int i;
    int count;
    tc = (countStruct *)threadcount;
// printf ("thread1 : I'm thread 1\n");

        for (i = 0; i < MAX; i++)
        {
// printf("thread[%d] : number = %d, i = %d\n", *tc, number, i);

        pthread_mutex_lock(&mut);
//        usleep(500000);

        count = number;
        usleep(100);
                count++;
        number = count;
                pthread_mutex_unlock(&mut);
        printf("thread[%d] : number++ = %d, i = %d\n", tc->a, number, pthread_self());
// sleep(2);

        }
// printf("thread1 :主函数在等我完成任务吗?\n");

        pthread_exit(NULL);
}

//void thread_create(void)

//{

// int temp, k;

// memset(&thread, 0, sizeof(thread)); //comment1

// /*创建线程*/

//    for(k = 0; k < MAXTHREAD; k++)

//    {

////        sleep(1);

//        if((temp = pthread_create(&thread[k], NULL, thread1, (void *)&k)) != 0) //comment2

//

//            printf("thread create error!\n");

//        else

//            printf("thread[%d] is created\n", k);

//    }

//}

void thread_wait(void)
{
    int i;

    for(i = 0; i < MAXTHREAD; i++)
    {
        if(thread[i] != 0)
        {
            pthread_join(thread[i],NULL);
     printf("thread[%d] is finished\n", i);
        }
    }

}
int main()
{
    int temp,k;
    countStruct cs[MAXTHREAD];

        /*用默认属性初始化互斥锁*/
        pthread_mutex_init(&mut,NULL);
        printf("i'm main function, i'm creating threads\n");
    
    ///////////////////

        memset(&thread, 0, sizeof(thread)); //comment1

        /*创建线程*/
    for(k = 0; k < MAXTHREAD; k++)
    {
        cs[k].a = k;
        if((temp = pthread_create(&thread[k], NULL, thread1, (void *)&cs[k])) != 0) //comment2


            printf("thread create error!\n");
        else
            printf("thread[%d] is created\n", k);
    }
    ///////////////////

        
        printf("i'm main function, i'm waiting for my threads\n");
        thread_wait();
        return 0;
}


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