[juliantec_list] 多线程互斥问题

  • From: Linux Xp <xp2linux@xxxxxxxx>
  • To: "app-dev-in-linux@xxxxxxxxxxxxxx" <app-dev-in-linux@xxxxxxxxxxxxxx>
  • Date: Wed, 28 Dec 2011 11:28:29 +0800 (CST)

Hi:
     我在写一个寻找素数的多线程程序,
但是几次下来程序的执行结果不完全一样,
并且偶尔会出现段错误,不知道是什么问题。

我程序的思路是这样的:
1,通过命令行指定从哪里开始查找素数,并
指定需要查找多少个素数。
2,另外通过命令行参数来指定需要多少个线
程参与素数的查找。

下面是我的部分程序代码。
其中 isPrimeLL 是判断是否为素数的函数,
在另外一个静态库里面。

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


void *finder();
void *waiter_proc();
long long getNumber();
int isPrimeLL(long long n);

// global variables
long long n, *archive;
int m, l, primes_found = 0;
pthread_t *tid;
pthread_t waiter;
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;

int main(int argc, char *argv[])
{
   long i = 0;

   if(argc != 4)
   {
      fprintf(stderr, 
      "Usage: %s <starting number> <# of primes> <# of threads>\n", 
      argv[0]);
      
      return 1;
   }

   // starting num
   n = atoll(argv[1]);

   // number of primes to find
   m = atoi(argv[2]);
   archive = malloc(m * sizeof(long long));

   // numbers of thread
   l = atoi(argv[3]);
   tid = malloc(l * sizeof(pthread_t));

   for(i = 0; i < l; i++)
   {
      if(pthread_create(&tid[i], NULL, finder, NULL))
         return 1;
   }

   // waiter thread
   if(pthread_create(&waiter, NULL, waiter_proc, NULL))
      return 1;

   // wait for waiter thread to exit
   pthread_join(waiter, NULL);

   for(i = 0; i < m; i++)
   {
      printf("%llu\n", archive[i]);
   }

   free(archive);
   free(tid);

   return 0;
}

void *finder()
{
   long long number;
   while(1)
   {
      pthread_mutex_lock(&lock1);
      number = getNumber();
      pthread_mutex_unlock(&lock1);
      if(number != 0)
      {
         if(isPrimeLL(number))
         {
            pthread_mutex_lock(&lock2);
            archive[primes_found] = number;
            primes_found++;
            pthread_mutex_unlock(&lock2);
         }
      }
      else
      {
         pthread_exit(NULL);
      }
   }
}

void *waiter_proc()
{
   int i;

   // wait for finder threads to exit
   for(i = 0; i < l; i++)
   {
      pthread_join(tid[i], NULL);
   }
}

long long getNumber()
{
   if(primes_found < m)
   {
      return n++;
   }
   else
      return 0;
}

Learning, Just As Your Favourite Thing!

Maillist, See http://www.juliantec.info/mlist/mail-lists.html
JulBlog, See http://www.juliantec.info/julblog/summary.php
JulWiki, See http://www.juliantec.info/wiki/
JulJob, see http://www.juliantec.info/juljob/



Other related posts: