我正在嘗試使用 pthread_create() 創建 (3) 個執行緒,并按順序列印執行緒號和 ID,以進行 (5) 次迭代。
原諒我的代碼,我對 C 語言還很陌生,但是當我的執行緒創建被列印時,我看到了一個奇怪的模式。例如,我想要的輸出是:
Iteration: 1 of 5
Thread 1 (ID: 140671542023744)
Thread 2 (ID: 140671533631040)
Thread 3 (ID: 140671525238336)
Iteration: 2 of 5
Thread 1 (ID: 140671542023744)
Thread 2 (ID: 140671533631040)
Thread 3 (ID: 140671525238336)
Iteration: 3 of 5
Thread 1 (ID: 140671542023744)
Thread 2 (ID: 140671533631040)
Thread 3 (ID: 140671525238336)
Iteration: 4 of 5
Thread 1 (ID: 140671542023744)
Thread 2 (ID: 140671533631040)
Thread 3 (ID: 140671525238336)
Iteration: 5 of 5
Thread 1 (ID: 140671542023744)
Thread 2 (ID: 140671533631040)
Thread 3 (ID: 140671525238336)
我的實際輸出是:
Iteration: 1 of 5
Thread 1 (ID: 140671542023744)
Thread 2 (ID: 140671533631040)
Thread 3 (ID: 140671525238336)
Iteration: 2 of 5
Thread 1 (ID: 140671525238336) <-- Order starts reversing here for some reason
Thread 2 (ID: 140671533631040)
Thread 3 (ID: 140671542023744)
Iteration: 3 of 5
Thread 1 (ID: 140671542023744)
Thread 2 (ID: 140671533631040)
Thread 3 (ID: 140671525238336)
Iteration: 4 of 5
Thread 1 (ID: 140671525238336)
Thread 2 (ID: 140671533631040)
Thread 3 (ID: 140671542023744)
Iteration: 5 of 5
Thread 1 (ID: 140671542023744)
Thread 2 (ID: 140671533631040)
Thread 3 (ID: 140671525238336)
建議將不勝感激。它快把我逼瘋了。我的代碼發布在下面:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
pthread_t threads[3];
pthread_mutex_t mutex;
void * printThread(void * arg) {
pthread_t id = pthread_self(); // Get pthread ID
printf("\t\tThread %d (ID: %ld)\n", arg 1, id); // Print thread creation and ID, account for zero index
return NULL;
}
int main(void) {
int i, j;
int error;
if (pthread_mutex_init( & mutex, NULL) != 0) {
printf("\n Error: pthread_mutex_init failure. [%s]\n", strerror(error));
return 1;
} // Catch and print pthread_mutex_init error
printf("Begin multithreading...\n");
/* Create and print (3) threads by ID, for (5) iterations */
for (i = 0; i < 5; i ) {
printf("\t\nIteration: %d of 5\n\n", i 1);
for (j = 0; j < 3; j ) {
error = pthread_create( & (threads[j]), NULL, & printThread, (void * ) j); // Create new thread
if (error != 0)
printf("\nError: pthread_create failure. [%s]\n", strerror(error));
sleep(2);
} // Catch and print pthread_create error
/* Syncrhonize threads */
pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
pthread_join(threads[2], NULL);
}
printf("\nMultithreading complete.\n");
/* Cleanup threads and mutex */
pthread_exit( & threads);
pthread_mutex_destroy( & mutex);
return 0;
}
uj5u.com熱心網友回復:
pthreads 是一個非常不透明和通用的 API,因此使用 pthreads API 的應用程式代碼可以很容易地移植到盡可能多的(通常是完全不同的)平臺上。
作為不透明哲學的一部分,pthreads 對回傳的 ID 值的唯一限制pthread_create()是每個有效(即尚未加入的)執行緒的 ID 對于行程中的所有其他有效執行緒都是唯一的。除此之外,所有行為都留給平臺的 pthreads 實作來處理,但它認為合適。
鑒于此,我認為發布的代碼中沒有任何錯誤。唯一的錯誤是假設回傳的 IDpthread_create()應該或將遵循執行緒 ID 唯一性之外的一些附加規則——這不是一個有效的假設。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/451293.html
上一篇:與C 中的“版本控制”同步
