0
這應該是創建兩個線程,讓他們宣佈他們的ID和他們分配給PID。一些基本的錯誤檢查也被執行。這是一個過於複雜的pthreads代碼?
有沒有更簡單的方法來做到這一點而不犧牲錯誤檢查?
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[1];
void* doSomething(void *arg)
{
int i = 0;
pthread_t id = pthread_self();
const char* a[2];
a[0]="Client(1)";
a[1]="Server(2)";
while (i<2)
{
if (pthread_equal(id,tid[i]))
printf("\n I'm the %s! My ID is: %ld. Our PID is= %d\n",a[i], (long int)&(tid[i]) , getpid());
i++;
}
pthread_exit(0);
}
int main(void)
{
int i = 0;
int error;
while(i < 2)
{
error = pthread_create(&(tid[i]), NULL, &doSomething, NULL);
if (error != 0){
printf("\n Error creating thread %d:[%s]",i+1, strerror(error));
}
else{
if(i==0){
printf("\n Principal thread: Client thread (%i) created! Thread ID: %ld \n", i+1, (long int)&(tid[0]));
}
if(i==1){
printf("\n Principal thread: Server thread (%i) created! Thread ID: %ldn", i+1, (long int)&(tid[1]));
}
i++;
}
}
if (pthread_join((tid[0]), NULL) == 0){
printf ("\n Client has closed \n");
} else {
printf ("\n Client closed with an error \n");
}
if (pthread_join((tid[1]), NULL) == 0){
printf ("\n Server has closed \n");
}else{
printf ("\nClient closed with an error \n");
}
return 0;
}
不太複雜;只是調用未定義的行爲。因爲你已經定義了'pthread_t tid [1]',所以你有'if(pthread_equal(id,tid [i]))''它將訪問'tid [0]'(OK)和'tid [1]'(不是OK) ;'所以你正在訪問數組越界;誰知道發生了什麼。你在main()中的代碼應該使用'for'循環而不是'while'循環,所有的備件都分散在代碼中。它不應該訪問'tid'數組越界。 –
對於codereview,請在[codereview.se]上詢問,而不是在這裏。 – fuz
我投票結束這個問題作爲題外話,因爲它是關於代碼審查屬於[codereview.se]。 – fuz