0
我正在嘗試編寫一個多線程程序,它從命令行獲取數字列表,並使用單獨的工作線程計算各種統計值,例如平均值,總和等。我在這個程序中創建了三個線程,它編譯但我得到錯誤。我是C和線程編程的新手,請指導我將數據傳遞給線程進行計算? 這是我的代碼:線程對commad行輸入的數字列表執行統計計算?
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#define NUM_THREAD 3
int average, min, max;
void *
doSomeThing(void *param)
{
//int *id_ptr, taskid;
int *argv = (int *) param;
sleep(1);
//id_ptr=(int *) threadid;
//taskid= *id_ptr;
int j;
int sum = 0;
int upper = atoi(param);
sleep(1);
pthread_t id = pthread_self();
unsigned long i = 0;
if (id = 1) {
int i;
for (i = 0; i < upper; i++) {
sum += argv[i];
}
printf("sum of no's is :\n", sum);
}
if (id = 2) {
printf("\n Second thread processing\n");
}
if (id = 3) {
printf("\n Third thread processing\n");
}
for (i = 0; i < -1; i++);
{
pthread_exit(NULL);
}
}
int
main(int argc, char *argv[])
{
pthread_t threads[NUM_THREAD];
pthread_attr_t attr;
int *taskid[NUM_THREAD];
int i = 0;
int t;
int err;
//int input,a;
if (argc != 2) {
fprintf(stderr, "usage: a.out <integer value>\n");
return -1;
}
/*
printf("how many no's do u want to evaluate?:\n");
scanf("%d", &input);
printf("Enter the no's:\n");
for (a = 0; a < input; a++) {
arr[a] = (int) malloc(sizeof(int));
scanf("%d", &arr[a]);
printf("data:", &arr[a]);
}
*/
pthread_attr_init(&attr);
for (t = 0; t < NUM_THREAD; t++) {
taskid[t] = (int *) malloc(sizeof(int));
*taskid[t] = t;
printf("In main: creating thread %d\n", t);
err = pthread_create(&threads[t], &attr, doSomeThing, argv[1]);
if (err) {
printf("Error; return code from pthread_create() is %d\n",
err);
exit(-1);
}
}
for (t = 0; t < NUM_THREAD; t++) {
pthread_join(threads[t], NULL);
printf("Joining thread %d\n", t);
}
pthread_exit(NULL);
}
可怕的格式。 –
歡迎來到Stack Overflow。請閱讀[關於]頁面。讀取縮進的代碼很難;請確保您的代碼正確呈現縮進。不要使用標籤;將它們替換爲(四個推薦的)空間。請詳細解釋你所得到的錯誤,並提供一個SSCCE([Short,Self-Contained,Correct Example](http://sscce.org/)),以便人們更容易複製你所看到的問題。輸入數據和其他代碼(例如啓動線程的'main()')可能也是相關的。 ......哦......'main()'在那裏,縮進了5級!噢! –
是什麼讓你認爲pthread_create指定一個不錯的小數字,如1,2,3作爲thread_id?當你調用'pthread_self()'時,你不可能得到1,2或3.你最終應該''釋放'你從'malloc'獲得的內存。 –