gcc (GCC) 4.6.3
c89
你好,
我只是想知道这是否是处理 main 创建的工作线程/后台线程的最佳方法?
我这样做对吗?这是我第一次完成任何多线程程序。只是想确保我走在正确的轨道上,因为这必须扩展以添加更多线程。
我有一个线程用于发送消息,另一个线程用于接收消息。
非常感谢您的任何建议,
int main(void)
{
pthread_t thread_send;
pthread_t thread_recv;
int status = TRUE;
/* Start thread that will send a message */
if(pthread_create(&thread_send, NULL, thread_send_fd, NULL) == -1) {
fprintf(stderr, "Failed to create thread, reason [ %s ]",
strerror(errno));
status = FALSE;
}
if(status != FALSE) {
/* Thread send started ok - join with the main thread when its work is done */
pthread_join(thread_send, NULL);
/* Start thread to receive messages */
if(pthread_create(&thread_recv, NULL, thread_receive_fd, NULL) == -1) {
fprintf(stderr, "Failed to create thread for receiving, reason [ %s ]",
strerror(errno));
status = FALSE;
/* Cancel the thread send if it is still running as the thread receive failed to start */
if(pthread_cancel(thread_send) != 0) {
fprintf(stderr, "Failed to cancel thread for sending, reason [ %s ]",
strerror(errno));
}
}
}
if(status != FALSE) {
/* Thread receive started ok - join with the main thread when its work is done */
pthread_join(thread_recv, NULL);
}
return 0;
}
用于发送消息的工作线程/后台线程示例,仅作为示例
void *thread_send_fd()
{
/* Send the messages when done exit */
pthread_exit(NULL);
}