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);
}
最佳答案
这种构造可能唯一合理的情况是只交换一条消息,即使那样,也可能存在一些问题。
如果在应用程序运行期间要不断交换消息,则更常见的做法是将两个线程都编写为循环并且从不终止它们。这意味着没有持续的创建/终止/销毁开销,也没有死锁生成器(也称为连接)。它确实有一个缺点 - 这意味着您必须参与线程间通信的信号、队列等,但如果您编写许多多线程应用程序,这无论如何都会发生。
无论哪种方式,通常首先启动 rx 线程。如果先启动 tx 线程,则有可能在 rx 线程启动之前 rx 数据被重新调整并丢弃。
关于创建和销毁线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10047024/