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);
}