创建和销毁线程
问题描述:
gcc (GCC) 4.6.3
c89
你好,创建和销毁线程
我只是想知道这是否是处理由主创建的工作/后台线程的最佳方式?
我这样做对吧?这是我第一次完成任何多线程程序。只是想确保我在正确的轨道上,因为这将不得不扩展到添加更多的线程。
我有一个线程用于发送消息,另一个用于接收消息。
非常感谢您的任何建议,工人/后台线程的
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);
}
答
当这种结构的可能有正当理由的唯一时间是如果只有一个消息被交换,那么即使这样,也可能会有一些问题。
如果在应用程序运行期间不断交换消息,那么将两个线程编写为循环并且永不终止它们更为常见。这意味着不会持续创建/终止/销毁开销,也不会产生死锁生成器(AKA连接)。它有一个缺点 - 这意味着你必须涉及线程间通信的信号,队列等,但是如果你编写了很多多线程应用程序,这将会发生。
无论哪种方式,通常先启动rx线程。如果首先启动tx线程,那么rx数据在rx线程启动之前可能会被重新调用并丢弃。
答
这是每条消息完成一次吗?看起来这个调用创建了一个线程来发送1个消息,另一个线程等待1个响应。然后,这个电话,我假设整个节目,只是等待整个事情完成。假设接收者在发送者完成发送之前不能做任何事情,这对于提高程序的真实或感知性能没有任何作用。具体来说,我们需要知道发件人和收件人的真实情况,然后才能确定是否有任何好处。对于任何好处,发件人线程和接收器线程必须有他们可以同时执行的工作 ....不是连续的。如果意图是不让程序等待发送和接收事务,那么这根本就没有这样做。