【发布时间】:2012-11-29 17:14:51
【问题描述】:
我有这个代码
我的范围是:程序创建 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 现在不同了。
【问题讨论】:
-
请注意,您的代码不可移植。将
pthread_t转换为unsigned int的结果是完全不可预测的。 (在某些平台上,您可能有两个具有不同 ID 的线程,但在转换为unsigned int时看起来相同。同一个线程甚至可能有多个这样的结果,因此不相等的值甚至不能证明不同的线程。那是为什么你需要pthread_equal。) -
是的,我知道,这仅用于测试线程调用,我的下一个代码将使用 syscall(SYS_gettid) 来管理 TID。非常感谢
标签: linux multithreading pthreads