0

I am trying to write a C program which involves threads. The user inputs a number and a thread is created to compute the sin value for that number. Right now when I compile and run the code the thread never seems to terminate. I have also included the steps I am using to compile this program in the comments in my source code.

#include <stdio.h>
#include <math.h>
#include <pthread.h>
/*
compile:
1.  gcc MyName.c -o MyName -lm -lpthread
2. ./MyName.c
*/

double result;
double x;  

void *calcSin(void *u);

int main()
{
    pthread_t tid;
    pthread_attr_t attr;

    pthread_attr_init(&attr); //Set thread attributes
    pthread_create(&tid, &attr, calcSin, NULL); //Create thread
    pthread_join(tid,NULL); //Wait until new thread completes

    printf("First thread completed here is sin: %lf\n", result);
    return 0;
}

void *calcSin(void *u)
{
    result = 0;
    printf("Enter first number: \n");
    scanf("%lf\n",&x);   

    result = sin(x);
    pthread_exit(0);
}


  • Did you test that this code works if you just call `calcSin` directly without a thread? – David Schwartz Apr 23 '20 at 18:09
  • https://stackoverflow.com/a/41767965/1216776 – stark Apr 23 '20 at 18:12
  • FYI, in any _meaningful_ multi-threaded program, you'd have your main thread do something else after starting the new thread and before joining it. If the main thread doesn't do anything concurrently with the new thread, then it's really just a slightly slower and more complicated equivalent of writing a single-threaded program. – Solomon Slow Apr 23 '20 at 18:14

1 Answers1

1

Just remove the '\n' from scanf and it should work. scanf does it automatically.

MrBens
  • 1,227
  • 1
  • 9
  • 19
  • How would you compile the math.h and pthread.h libraries together? – Soccerplayer97 Apr 24 '20 at 01:11
  • You may dynamically link the libraries with you program. Use **-lm** and **-lpthread** flags (that's -l as in lion and not I as in Iron) .As a side note: math.h and pthread.h are not the libraries themselves, just the header files of them, When you dynamically link the libraries, you're actually telling the linker to look in its path for the libraries you wish to use, By adding **-lmy_lib**, the linker search for a library name **libmy_lib.so**. So here, the libraries are **libmath.so** and **libpthread.so**. – MrBens Apr 24 '20 at 06:47