我有这个代码
我的范围是:程序创建 MAX_THREAD 线程,在这种情况下为三个,每个线程打印 Thread-ID 并退出。
#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);
}
输出是:
thread 0: - TID 3075976048 - Address 0xb757ab70
thread 1: - TID 3075976048 - Address 0xb757ab70
thread 2: - TID 3075976048 - Address 0xb757ab70
我不明白为什么只有一个线程!
我对这个声明有疑问:
pthread_t thr[MAX_THREAD];
我可以创建一个包含三个线程的数组,或者这只是一个线程????
解决了
新代码(我刚刚将 pthread_joiun() 放在 for 循环之外)
#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);
}
输出是:
thread '1' - TID 8780 - Address 0x224c
thread '0' - TID 8779 - Address 0x224b
thread '2' - TID 8781 - Address 0x224d
地址和线程 ID 现在不同了。