2013-05-03 73 views
0

我有在C.下面的代碼的問題基本上我想創建兩個線程並給他們兩者的「ergebnis」的整數值。在此之後,線程必須單獨計算該值並打印出各自的結果。Ç - 指針問題和空隙方法問題

在編譯時我得到這個錯誤:

3.2.c: In function ‘erhoehenumeins’: 
3.2.c:10:13: warning: dereferencing ‘void *’ pointer [enabled by default] 
3.2.c:10:13: error: void value not ignored as it ought to be 
3.2.c: In function ‘verdoppeln’: 
3.2.c:20:18: error: invalid operands to binary * (have ‘void *’ and ‘int’) 

代碼:

#include <sys/types.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <pthread.h> 
#include <stdlib.h> 

void *erhoehenumeins(void * dummy) { 
    printf("Thread erhoehenumeins() wurde gestartet\n"); 
    int temp; 
    temp= dummy+1; 
    printf("Thread erhoehenumeins() wurde beendet\n"); 
    printf("Ergebnis=%d\n",temp); 
} 
void *verdoppeln(void * dummy) { 
    printf("Thread verdoppeln() wurde gestartet\n"); 
    int temp=dummy*2; 
    printf("Thread verdoppeln() wurde beendet\n"); 
    printf("Ergebnis=%d\n",temp); 
} 

int main() { 
    int ergebnis=3; 
    pthread_t thread1, thread2; 
    // Thread 1 erzeugen 
    pthread_create(&thread1, NULL, &erhoehenumeins, &ergebnis); 

    // Thread 2 erzeugen 
    pthread_create(&thread2, NULL, &verdoppeln, &ergebnis); 

    // Main-Thread wartet auf beide Threads. 
    pthread_join(thread1, NULL); 
    pthread_join(thread2, NULL); 
    printf("\nHaupt-Thread main() wurde beendet\n"); 
    exit(0); 
} 

感謝您的幫助!

+0

好,你不會從你的功能中爲初學者返回任何東西...... – 2013-05-03 22:11:40

+0

只是一個側面說明:你的縮進(或者說缺少它)使得閱讀變得更難它需要。關於您的問題:http://pastebin.com/1XNrKfBc – ccKep 2013-05-03 23:02:33

回答

1

在行

int temp=dummy*2; 

dummyvoid * - 編譯器不能被2

乘以這個也許你應該這樣做」

int temp = (*(int *)dummy)*2; 
+0

非常感謝您的快速回答。 Wehen我按照你的解釋我的錯誤:3.2.c:在「verdoppeln」功能: 3.2.c:20:8:警告:賦值時將整數指針沒有施放[默認啓用] – 2013-05-03 22:48:56

+0

我看不到爲什麼;也許你應該用新的代碼編輯你的問題。 – 2013-05-03 22:55:32

1

這樣做:

void * erhoehenumeins(void * dummy) 
{ 
    int * p = (int *) dummy; 
    ++*p; 

    return NULL; 
} 

和:

int ergebnis = 3; 
pthread_create(&thread1, NULL, &erhoehenumeins, &ergebnis); 

這當然是未定義的行爲,並完全打破,但它應該現在就做。