First, paste the code in this section
//thread.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_N 1000000
#define MAX_THREADS 100
int nthreads,
n,
prime[MAX_N+1],
nextbase;
int work[MAX_THREADS];
pthread_mutex_t nextbaselock = PTHREAD_MUTEX_INITIALIZER;
pthread_t id[MAX_THREADS];
void crossout(int k){
int i;
for(i = k;i*k <= n;i++){
prime[i*k] = 0;
}
}
void * worker(int tn){
int lim,base;
do{
pthread_mutex_lock(&nextbaselock);
base = nextbase+=2;
//pthread_mutex_unlock(&nextbaselock);
if(base*base <=lim){
work[tn]++;
if(prime[base])
crossout(base);
}else
return 0;
}while(1);
}
int main(int argc,char **argv){
int nprimes,
totwork,
i;
void *p;
n = atoi(argv[1]);
nthreads = atoi(argv[2]);
for( i = 2;i <= n;i++)
prime[i]= 1;
crossout(2);
nextbase =1;
for( i= 0;i < nthreads;i++)
pthread_create(&id[i],NULL,(void*)worker,(void*)i);
totwork = 0;
for(i =0;i < nthreads;i++){
pthread_join(id[i],&p);
printf("%d values of base done\n",work[i]);
totwork +=work[i];
}
printf("%d total values of base done\n",totwork);
nprimes = 0;
for(i = 2;i <= n;i++)
if(prime[i]) nprimes++;
printf("the number of primes found was %d\n",nprimes);
}
The above is seeking a range of multi-threaded programming of prime numbers, the compiler need gcc -g thread.c -lpthread
to add thread link library, or programming error
after compilation we enter gdb, a command r 100 3
post and found the program stalled, as
the picture above you can see that there is a thread has quit, there are three threads, a total of four threads, which are a main thread and three computing threads. Exit is the computational thread, but why do the program will Caton, by ctr + c will suspend the program, see the thread situation
asterisk indicates the currently running thread. Use backtrace
to view the current thread's call stack, as
found in the call stack for the current thread only two functions, but also know the main thread, because the underlying function is the main function calls.
Use thread id
to switch the thread 3, view the call stack case
found frame 3 and frame 2 is to acquire the lock is suspended, understand this, because there is no thread 3 has been suspended obtain a lock, the same thread 4 is also the case, it is found that the biggest culprit is the thread 2 is not due to release the lock before gg, it is where
we deleted the comment recompile it again. Story rather than
the current gdb have learned in this, until after the other, and then updated,