多进程多线程测试代码

#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

/*cpu个数,确定进程数*/
#define cpunum 2

/*调试开关*/
#define debug 0

/*多个线程调用该函数*/
void *thrd_fun(void *data);

struct THRD{
    pid_t ppid;
} thrddata;

/*多个进程调用该函数*/
int callFuncation(int number);

void main()
{
    pid_t pid;
    int i;
    
    /*根据定义的cpu个数确定fork进程数目*/
    for(i=0;i<cpunum;i++)
    {
        pid=fork();
        if(pid==0)
        {
            /*子进程调用函数*/
            callFuncation(i);
            exit(-1);
        }
        else if(pid < 0)
        {
            fprintf(stdout,"fork error!\n");
            exit(-1);
        }
    }
    wait(NULL);
    fprintf(stdout,"pid = [%d]\n",getpid());
    exit(0);
}

int callFuncation(int number)
{
    int thread_num=0;

    /*定义最大线程数*/
    pthread_t thread[16];
    fprintf(stdout,"fork number [%d] ppid = [%d]\n",number,getpid());
    thrddata.ppid=getpid();
    void *tret;
    for(thread_num=0;thread_num<5;thread_num++)
    {
        /*多个线程调用函数接口*/
        if(pthread_create(&thread[thread_num],NULL,thrd_fun,(void *)&thrddata) !=0)
        {
            fprintf(stdout,"thread create error!\n");
            return -1;
        }

        /*合并线程,确保全部线程执行完后,销毁线程,返回主函数*/
        if (pthread_join(thread[thread_num],&tret)!=0) 
        {
            fprintf(stdout, "Join thread %d error!\n",thread_num);
            return (-1);
        }
        else if(debug)fprintf(stdout, "Join thread %d success!\n",thread_num);
    }
}

/*线程函数*/
void *thrd_fun(void *data)
{
    struct THRD *thdata;
    thdata=(struct THRD *)data;
    fprintf(stdout,"thd_data is [%d]!\n",thdata->ppid);
    pthread_exit(NULL);
}

代码是N个月前写的,今天加的注释,如果有任何不妥之处,望不吝指出。

转载于:https://my.oschina.net/u/1035860/blog/228424

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值