新闻  |   论坛  |   博客  |   在线研讨会
pthread create
xinjinlong | 2010-11-03 23:42:02    阅读:13108   发布文章

simple one
#include <pthread.h>
#include <stdio.h>
void* print_xs(void* unused){
    while(1)
        fputc('x',stderr);
    return NULL;

}
int main()
{
    pthread_t thread_id;
    /*create a new thread .the new thread will run
      the print_xs function*/
    pthread_create(&thread_id,NULL,&print_xs,NULL);
    while(1){
        fputc('o',stderr);
    }
    return 0;


}
pass data to thread
#include <pthread.h>
#include <stdio.h>
struct char_print_parms
{
    char character;
    int count;
};
void* char_print(void* parameters)
{
    struct char_print_parms* p =(struct char_print_parms*)parameters;
    int i ;
    for(i=0 ; i<p->count;i++)
      fputc(p->character,stderr);
    return NULL;

}
int main()
{
    pthread_t thread1_id;
    pthread_t thread2_id;
    struct char_print_parms thread1_args;
    struct char_print_parms thread2_args;

    thread1_args.character = 'x';
    thread1_args.count = 30000;
    pthread_create(&thread1_id,NULL,&char_print,&thread1_args);
   

    thread2_args.character = 'o';
    thread2_args.count = 20000;
    pthread_create(&thread2_id,NULL,&char_print,&thread2_args);

    pthread_join(thread1_id,NULL);
    pthread_join(thread2_id,NULL);

    return 0;
}

return data from thread
#include <pthread.h>
#include <stdio.h>

/* Compute successive prime numbers (very inefficiently).  Return the
   Nth prime number, where N is the value pointed to by *ARG.  */

void* compute_prime (void* arg)
{
  int candidate = 2;
  int n = *((int*) arg);

  while (1) {
    int factor;
    int is_prime = 1;

    /* Test primality by successive division.  */
    for (factor = 2; factor < candidate; ++factor)
      if (candidate % factor == 0) {
        is_prime = 0;
        break;
      }
    /* Is this the prime number we're looking for?  */
    if (is_prime) {
      if (--n == 0)
        /* Return the desired prime number
         * as the thread return value.  */
        return (void*) candidate;
    }
    ++candidate;
  }

  printf("The %dth prime number \n", candidate);
  return NULL;
}

int main ()
{
  pthread_t thread;
  int which_prime = 5000;
  int prime;

  /* Start the computing thread, up to the 5000th prime number.  */
  pthread_create (&thread, NULL, &compute_prime, &which_prime);
  /* Do some other work here...  */
  /* Wait for the prime number thread to complete, and get the
   * result.  */
  pthread_join (thread, (void*) &prime);
  /* Print the largest prime it computed.  */
  printf("The %dth prime number is %d.\n", which_prime, prime);
  return 0;
}
 cc -o primes  primes.c -lpthread

*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。

参与讨论
登录后参与讨论
五湖四海皆朋友
最近文章
浅谈MIPS的MMU(二)
2016-08-16 19:33:41
浅谈MIPS的MMU(一)
2016-05-05 10:55:06
推荐文章
最近访客