1
這是我的問題。例如,我在我的程序中有一個操作A,它需要一直工作(就像一個被稱爲每秒15次的函數)。操作A收集大量數據。然後用戶觸發器將這些大數據導出到文件。該操作B(即將數據導出到文件)應該在後臺執行,以便操作A不停止。在C中執行背景的最佳方法
我可以執行backgrounding使用並行線程這樣的:
#include <stdio.h>
#include <pthread.h>
void *threada() {
int i = 0;
for(i = 0;i < 1000;i++) {
printf("This is new thread!\n");
}
pthread_exit(NULL);
}
int main() {
int i = 0;
pthread_t thread;
for(i = 0;i < 105;i++) {
printf("This is current thread!\n");
if(i == 100) {
pthread_create(&thread, NULL, threada, NULL);
}
}
pthread_exit(NULL);
return 0;
}
或者有另一種方式做到這一點?
你也可以在後臺創建一個新的進程來完成這項工作。 – Shiping
使用叉子時,我應該關心什麼問題?例如,當父進程死了的時候子進程結束了嗎? – PeMaCN
在你的主線程中,使用'pthread_join(thread,NULL)'等待你的工作線程完成,而不是在返回調用之前的'pthread_exit(NULL)'。 – Scab