I have this code
My scope was: the program creates MAX_THREAD threads, three in this case, each thread prints Thread-ID and exits.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#define MAX_THREAD 3
void *thr_func(void *arg);
int main(void) {
pthread_t thr[MAX_THREAD];
int i, thr_err;
/* I expected three threads ... but there is only one */
for (i=0; i<MAX_THREAD; i++) {
printf("thread %d: - ", i);
if ((thr_err = pthread_create(&thr[i],NULL, thr_func, NULL)) != 0) {
fprintf(stderr, "Err. pthread_create() %s\n", strerror(thr_err));
exit(EXIT_FAILURE);
}
if (pthread_join(thr[i], NULL) != 0) {
fprintf(stderr, "Err. pthread_join() %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
}
return(EXIT_SUCCESS);
}
void *thr_func(void *arg)
{
pthread_t tid = pthread_self();
printf("TID %lu - Address 0x%x\n", tid, (unsigned int)pthread_self());
pthread_exit((void*)0);
}
output is:
thread 0: - TID 3075976048 - Address 0xb757ab70
thread 1: - TID 3075976048 - Address 0xb757ab70
thread 2: - TID 3075976048 - Address 0xb757ab70
I don’t understand why there is only one thread!
I have a doubt on this declaration:
pthread_t thr[MAX_THREAD];
Can i create an array of three threads or this is only one thread ????
SOLVED
New code (I’ve just put pthread_joiun() outside of for loop)
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>
#define MAX_THREAD 3
void *thr_func(void *thr_num);
int main(void) {
pthread_t thr[MAX_THREAD];
int i, thr_err;
for (i=0; i<MAX_THREAD; i++) {
if ((thr_err = pthread_create(&thr[i],NULL, thr_func, (void*)i)) != 0) {
fprintf(stderr, "Err. pthread_create() %s\n", strerror(thr_err));
exit(EXIT_FAILURE);
}
}
for (i=0; i<MAX_THREAD; i++) {
if (pthread_join(thr[i], NULL) != 0) {
fprintf(stderr, "Err. pthread_join() %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
}
return(EXIT_SUCCESS);
}
void *thr_func(void *thr_num)
{
pthread_t tid;
if ((tid = syscall(SYS_gettid)) == -1) {
fprintf(stderr, "Err. syscall() %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
printf("thread '%d' - TID %lu - Address 0x%x\n",
(int)thr_num, tid, (unsigned int)tid);
pthread_exit((void*)0);
}
Output is:
thread '1' - TID 8780 - Address 0x224c
thread '0' - TID 8779 - Address 0x224b
thread '2' - TID 8781 - Address 0x224d
Addresses and thread-ID now are different.
You are likely getting the same TID and address precisely because you
pthread_join()each thread before starting the next one. Thepthreadslibrary seems to be a bit lazy about reclaiming the associated data structures (probably for efficiency), so the next thread you spawn just uses the same data structures the previous one did. Try writing two loops, one to create the threads, then another one to do thepthread_join()s after all the threads have been created.