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$ 

你可能感兴趣的:(thread,多线程,C++,c,C#)