我繼續昨天的幫助,並且在子線程中添加了另一個代碼。基本上,當用戶輸入stdin時,子線程應該讀取它並將其返回給父線程。但是,打印完輸出後,應將代碼重定向回到子線程並等待用戶按Enter鍵,一旦用戶按下Enter鍵,代碼應退出。這是工作,但我已經使用睡眠(),我只想使用互斥體(),當我評論sleep(),然後下面的代碼首先打印(「按回車」),然後父代碼打印實際輸入。如何使用c編程中的子線程中的互斥處理同步
/*Required header files are added*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
/*this structure will hold the string of user input and the lock variable has created*/
struct thread_main
{
char *buffer;
char *bufferparent;
pthread_mutex_t lock;
pthread_mutex_t lock1;
} td;
/*it is a child thread, and store the user value in a buffer variable which has been declared in the thread_main structure*/
static void *thread(void *buff)
{
/*the pointer has assigned to the structure, so we can get the values of a buffer array*/
struct thread_arguments *arg = buff;
//the previous code
pthread_mutex_unlock(&td.lock);
pthread_mutex_destroy(&td.lock);
sleep(1); // I want to ignore this.
pthread_mutex_init(&td.lock, 0);
pthread_mutex_lock(&td.lock);
printf("press enter");
/*this code will read buffer and check the enter*/
pthread_mutex_unlock(&td.lock);
pthread_mutex_destroy(&td.lock);
return NULL;
}
上面的代碼看起來不像C++ –
線程函數中'arg'的大小是指針的大小;顯然,您正在64位機器上使用32位機器或32位版本。您可能需要使用指針和大小創建一個結構,並將指向該結構的指針傳遞給線程函數。 –
@LưuVĩnhPhúc該標籤已被刪除 –