Thread: a issue in thread programming

  1. #1
    Registered User
    Join Date
    Oct 2013
    Posts
    18

    a issue in thread programming

    I have to create two threads. Then one thread will take input by using scanf function and then another thread will print the input value. How to do that. My following program is giving segmentation fault.
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<pthread.h>
    #include<unistd.h>
    void *scan(void *s)
    {
    int *s1=(int *)s;
    scanf("%d",s1);
    pthread_exit((void *)s1);
    }
    void *print(void *s)
    {
    int *s1=(int *)s;
    printf("%d",(*s1));
    }
    int main()
    {
    pthread_t tid1,tid2;
    int *s;
    pthread_create(&tid1,NULL,scan,NULL);
    pthread_join(tid1,(void **)&s);
    sleep(5);
    pthread_create(&tid2,NULL,print,(void *)s);
    pthread_join(tid2,NULL);
    return 0;
    }
    Last edited by mrityunjay23; 01-24-2019 at 02:20 AM. Reason: wrong title

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,436
    Well you pass a NULL pointer to scan, which you then dereference.

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<pthread.h>
    #include<unistd.h>
    void *scan(void *s)
    {
        int *s1=malloc(sizeof(int));
        scanf("%d",s1);
        pthread_exit(s1);
    }
    void *print(void *s)
    {
        int *s1=s;
        printf("%d",*s1);
        free(s1);
        return NULL;
    }
    int main()
    {
        pthread_t tid1,tid2;
        void *temp;
        pthread_create(&tid1,NULL,scan,NULL);
        pthread_join(tid1,&temp);
        sleep(5);
        pthread_create(&tid2,NULL,print,temp);
        pthread_join(tid2,NULL);
        return 0;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Thread Issue
    By ghferrera in forum C Programming
    Replies: 2
    Last Post: 07-25-2014, 01:34 PM
  2. Replies: 3
    Last Post: 11-20-2011, 12:01 AM
  3. C++ thread inside a class hang issue
    By diefast9 in forum C++ Programming
    Replies: 11
    Last Post: 10-21-2009, 07:18 AM
  4. Replies: 3
    Last Post: 11-16-2006, 04:23 AM
  5. Replies: 8
    Last Post: 01-17-2006, 05:39 PM

Tags for this Thread