c-简单多线程(委托模型)

委托模型,即有一个BOSS线程,就是主线程,产生woker线程,boss线程和worker线程并发执行。

BOSS线程的主要任务是创建worker线程,将工作线程放入队列中,当有工作可处理时,唤醒 工作线程。

/* Create a new thread, starting with execution of START-ROUTINE getting passed ARG. Creation attributed come from ATTR. The new handle is stored in *NEWTHREAD. */

extern int pthread_create (pthread_t *__restrict __newthread,

__const pthread_attr_t *__restrict __attr,

void *(*__start_routine) (void *),

void *__restrict __arg) __THROW __nonnull ((1, 3));

/* Obtain the identifier of the current thread. */

extern pthread_t pthread_self (void) __THROW __attribute__ ((__const__));

//返回调用该函数的当前线程的pthread_t结构指针

/* Make calling thread wait for termination of the thread TH. The

exit status of the thread is stored in *THREAD_RETURN, if THREAD_RETURN

is not NULL.

This function is a cancellation point and therefore not marked with

__THROW. */

extern int pthread_join (pthread_t __th, void **__thread_return);//__thread_return退出状态

//pthread_join导致调用线程挂起它的执行,直到目标线程的结束。

main.c

#include <pthread.h>

#include <stdio.h>

 //2个工作线程,分别是累加和累乘

void *mycompadd(void *xx){//参数必须为void *,然后进行强制类型转换

  int sum=0; 

  int *x=(int *)(xx);

  for (int i=0;i<*x;i++){

    sum+=i;

  }

  printf("add%d\n",sum);    

}

void  *mycompchen(void *xx){//参数必须为void *,然后进行强制类型转换

  int sum=1; 

  int *x=(int *)(xx);

  for (int i=1;i<=*x;i++){

    sum*=i;  

  }

  printf("chen%d\n",sum);   

}

 

 

int main(){

  //main为boss线程,

  pthread_t threada,threadb;

  //创建worker线程,并执行线程

  int n=3;

  pthread_create(&threada,NULL,mycompadd,&n);//线程,线程属性,函数,参数。如果有多个参数,必须传结构指针

  pthread_create(&threadb,NULL,mycompchen,&n);//线程,线程属性,函数,参数

  //wait worker线程,并合并到BOSS线程来

  pthread_join(threada,NULL);

  pthread_join(threadb,NULL);

  return(0);

}

深未来技术原创文章,如转载,请注明来源http://deepfuture.iteye.com/ 

执行效果:
deepfuture@deepfuture-laptop:~/mytest$ gcc -lpthread -std=c99 -o main main.c
deepfuture@deepfuture-laptop:~/mytest$ ./main
add3
chen6
deepfuture@deepfuture-laptop:~/mytest$ 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值