Beginning Linux Programming Third Edition phần 7

bằng cách nhấn một phím chức năng, nhưng nó cũng phải đối phó với các thiết bị đầu cuối khác nhau bằng cách sử dụng Các máy chủ chức năng đọc lần đọc một tin nhắn bất cứ loại nào (có nghĩa là, từ khách hàng bất kỳ) từ hàng đợi, và nó sẽ trả về một phần dữ liệu (bỏ qua các loại) của tin nhắn. | Chapter 12 work_area 0 0 pthread_mutex_unlock work_mutex sleep 1 pthread_mutex_lock work_mutex while work_area 0 0 pthread_mutex_unlock work_mutex sleep 1 pthread_mutex_lock work_mutex time_to_exit 1 work_area 0 0 pthread_mutex_unlock work_mutex pthread_exit 0 cc -D_REENTRANT -I usr include nptl -o thread4 -L usr lib nptl -Ipthread . thread4 Input some text. Enter end to finish Whit You input 4 characters The Crow Road You input 13 characters end Waiting for thread to finish. Thread joined How It Works We start by declaring a mutex our work area and this time an additional variable time_to_exit. pthread_mutex_t work_mutex protects both work_area and time_to_exit define WORK_SIZE 1024 char work_area WORK_SIZE int time_to_exit 0 Then we initialize the mutex. res pthread_mutex_init work_mutex NULL if res 0 perror Mutex initialization failed exit EXIT_FAILURE Next we start the new thread. Here is the code that executes in the thread function pthread_mutex_lock work_mutex while strncmp end work_area 3 0 printf You input d characters n strlen work_area -1 492 POSIX Threads work_area 0 0 pthread_mutex_unlock work_mutex sleep 1 pthread_mutex_lock work_mutex while work_area 0 0 pthread_mutex_unlock work_mutex sleep 1 pthread_mutex_lock work_mutex time_to_exit 1 work_area 0 0 pthread_mutex_unlock work_mutex First the new thread tries to lock the mutex. If it s already locked the call will block until it is released. Once we have access we check to see whether we are being requested to exit. If we are requested to exit we simply set time_to_exit zap the first character of the work area and exit. If we don t want to exit we count the characters and then zap the first character to a null. We use the first character being null as a way of telling the reader program that we have finished the counting. We then unlock the mutex and wait for the main thread to run. Periodically we attempt to lock the mutex and when we succeed check whether the main thread has given us any

Không thể tạo bản xem trước, hãy bấm tải xuống
TÀI LIỆU MỚI ĐĂNG
13    121    2    01-06-2024
92    203    3    01-06-2024
30    2    1    01-06-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.