【发布时间】:2010-11-22 14:40:54
【问题描述】:
我正在调试 C、pthread 和 Linux 的多线程问题。在我的 MacOS 10.5.8 上,C2D 运行良好,在我的 Linux 计算机(2-4 核)上,它会产生不希望的输出。
我没有经验,因此我附上了我的代码。这相当简单:每个新线程再创建两个线程,直到达到最大值。所以没什么大不了的......就像我几天前想的那样。 我可以强制单核执行以防止我的错误发生吗?
我分析了程序执行,使用 Valgrind 进行检测:
valgrind --tool=drd --read-var-info=yes --trace-mutex=no ./threads
我在 BSS 段中遇到了一些冲突 - 这是由我的全局结构和线程计数器变量引起的。但是我可以通过强制执行单核来缓解这些冲突,因为我认为我的 2-4 核测试系统的并发调度是导致我的错误的原因。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_THR 12
#define NEW_THR 2
int wait_time = 0; // log global wait time
int num_threads = 0; // how many threads there are
pthread_t threads[MAX_THR]; // global array to collect threads
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; // sync
struct thread_data
{
int nr; // nr of thread, serves as id
int time; // wait time from rand()
};
struct thread_data thread_data_array[MAX_THR+1];
void
*PrintHello(void *threadarg)
{
if(num_threads < MAX_THR){
// using the argument
pthread_mutex_lock(&mut);
struct thread_data *my_data;
my_data = (struct thread_data *) threadarg;
// updates
my_data->nr = num_threads;
my_data->time= rand() % 10 + 1;
printf("Hello World! It's me, thread #%d and sleep time is %d!\n",
my_data->nr,
my_data->time);
pthread_mutex_unlock(&mut);
// counter
long t = 0;
for(t = 0; t < NEW_THR; t++){
pthread_mutex_lock(&mut);
num_threads++;
wait_time += my_data->time;
pthread_mutex_unlock(&mut);
pthread_create(&threads[num_threads], NULL, PrintHello, &thread_data_array[num_threads]);
sleep(1);
}
printf("Bye from %d thread\n", my_data->nr);
pthread_exit(NULL);
}
return 0;
}
int
main (int argc, char *argv[])
{
long t = 0;
// srand(time(NULL));
if(num_threads < MAX_THR){
for(t = 0; t < NEW_THR; t++){
// -> 2 threads entry point
pthread_mutex_lock(&mut);
// rand time
thread_data_array[num_threads].time = rand() % 10 + 1;
// update global wait time variable
wait_time += thread_data_array[num_threads].time;
num_threads++;
pthread_mutex_unlock(&mut);
pthread_create(&threads[num_threads], NULL, PrintHello, &thread_data_array[num_threads]);
pthread_mutex_lock(&mut);
printf("In main: creating initial thread #%ld\n", t);
pthread_mutex_unlock(&mut);
}
}
for(t = 0; t < MAX_THR; t++){
pthread_join(threads[t], NULL);
}
printf("Bye from program, wait was %d\n", wait_time);
pthread_exit(NULL);
}
我希望代码不会太糟糕。很长一段时间我都没有做太多的C。 :) 问题是:
printf("Bye from %d thread\n", my_data->nr);
my_data->nr 有时会解析高整数值:
In main: creating initial thread #0
Hello World! It's me, thread #2 and sleep time is 8!
In main: creating initial thread #1
[...]
Hello World! It's me, thread #11 and sleep time is 8!
Bye from 9 thread
Bye from 5 thread
Bye from -1376900240 thread
[...]
我现在没有更多的方法来分析和调试这个。 如果我调试它,它会起作用 - 有时。有时它不会:(
感谢您阅读这个冗长的问题。 :) 我希望我没有分享太多我目前无法解决的困惑。
【问题讨论】:
-
在这种情况下,我很抱歉我手头没有好的、基本的多线程教程——也许其他一些人可以指出一个好的?很抱歉,但目前我没有时间自己回答这个问题......
-
它可能不会产生您想要的结果,但您可以使用“taskset”来设置正在运行(或启动)进程的亲和性...
-
我想知道您的
threads数组是否溢出到您的num_threads变量中。
标签: c linux multithreading pthreads