c - Creating a thread and passing input through the parent -
i'm trying use mutex make thread wait user input parent thread. current problem i'm facing child doesn't wait, though have mutex lock , unlock, join in parent thread. also, unsure if struct being used correctly? main() , *chthread() using same instance of "lock"? understand when user input before thread creation works, requirements of exercise states meant pass information after thread created.
#define _gnu_source #include <stdio.h> #include <pthread.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <readline/readline.h> #include <readline/history.h> # define buffer_size 256 void *chthread(void *arg); struct { pthread_t pth; pthread_mutex_t lock; int ret; void* ex; } muinfo; int main(int argc, char *argv[]) { //struct mutex args; char line[buffer_size]; char *temp = null; pthread_mutex_init(&muinfo.lock, null); if((pthread_create(&muinfo.pth, null, chthread, line)) != 0) { perror("problem creating thread"); } using_history(); temp = readline("enter string: "); strcpy(line, temp); if((pthread_join(muinfo.pth, &muinfo.ex)) !=0) { perror("thread join error"); } free(temp); pthread_mutex_destroy(&muinfo.lock); pthread_exit(null); } void *chthread(void *arg) { //struct mutex args; pthread_mutex_lock(&muinfo.lock); char *line = (char*)arg; printf("testing %s\n", line); pthread_mutex_unlock(&muinfo.lock); pthread_exit(&muinfo.ret); //return null; }
as main problem, need lock mutex @ main first(likely after init it),
, unlock after getting input user,
child thread wait until main unlock.
pthread_mutex_init(&muinfo.lock, null); pthread_mutex_lock(&muinfo.lock); if((pthread_create(&muinfo.pth, null, chthread, line)) != 0) { perror("problem creating thread"); } using_history(); temp = readline("enter string: "); strcpy(line, temp); pthread_mutex_unlock(&muinfo.lock);
i remove using_history() , use delayed strcpy fixed string instead readline test,
, work fine me.
Comments
Post a Comment