与使用不同的框架相比,考虑到您在问题中提到了
pthread_join()
,您仍然可以通过POSIX C实现所需的效果。为此,您可以使用信号来确认并行任务完成的线程。在这种方法中,您需要为用户定义的信号(例如
SIGUSR1
)安装一个信号处理程序,创建一组具有不同任务的工作线程,并让它们在完成时向父线程发出信号。
下面的程序说明了这个尝试。在这个例子中,我使用
SIGUSR1
来通知父线程某些处理已经完成。父线程一直忙于执行一些I/O操作,直到被子线程中断。请注意,为了清晰起见,没有放置任何形式的错误处理代码。
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int value = 0;
volatile sig_atomic_t value_received = 0;
void handler(int signum) {
value_received = 1;
}
void *thread(void *parent) {
value = 1;
sleep(5);
pthread_kill((pthread_t)parent, SIGUSR1);
return NULL;
}
int main(void) {
struct sigaction action;
pthread_t child;
action.sa_handler = handler;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
sigaction(SIGUSR1, &action, NULL);
pthread_create(&child, NULL, thread, (void*)pthread_self());
pthread_detach(child);
while (!value_received) {
char buffer[0x100];
if (!fgets(buffer, sizeof buffer, stdin))
break;
printf("You typed: %s", buffer);
}
if (feof(stdin))
while (!value_received)
sleep(1);
printf("Value received: %i\n", value);
return EXIT_SUCCESS;
}
这个示例使用LinuxThreads实现的信号,与POSIX定义的相当不同。如果你关心可移植性或兼容性,上述解决方案应进一步修改。