pthread program results in segmentation fault - c

I've been trying to create a chat program in C with threads but it hasn't been working, so I decided to play with threads for a bit first. I'm trying to run a thread that prints "hello world", but it gives me a segmentation fault. I haven't been able to find the root of the problem so I came here. heres the code:
#include <stdio.h>
#include <pthread.h>
void* test(void * arg) {
printf("hello world\n");
return NULL;
}
int main() {
pthread_t test;
pthread_create(&test, NULL, (void *) test, NULL);
pthread_exit(NULL);
return 0;
}
There's probably a stupid reason why it's not working so I hope you guys wont have too much trouble finding it!

Your start routine name and thread id name are the same so I think compiler gets confused when you pass &test. Your code works by changing the thread id name.
#include <stdio.h>
#include <pthread.h>
void* test(void * arg) {
printf("hello world\n");
return NULL;
}
int main() {
pthread_t t;
pthread_create(&t, NULL, (void *) test, NULL);
pthread_exit(NULL);
return 0;
}

void* test(void * arg) { ... }
// vvvv
pthread_t test;
pthread_create(&test, NULL, (void *) test, NULL);
// ^^^^
That pthread_t variable is "hiding" the function name. In other words, you're calling some arbitrary uninitialised value as your function. That's unlikely to end well :-)
What you're doing is really no different to expecting the following program to output 7 (it won't):
#include <stdio.h>
int i = 7;
int main(void) {
int i = 42;
printf("%d\n", i);
return 0;
}
You could solve it simply by renaming your function to testFn, for example.

Related

Issues running commands in terminal

I have this assignment for Operating Systems, the code won't run in MAC terminal, I keep getting an issue that says, "Image". Is there any help I can get on this issue?
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
// These two functions will run concurrently
void* print_i(void *ptr)
{
printf("I am in i\n");
}
void* print_j(void *ptr)
{
printf("I am in j\n");
}
int main()
{
pthread_t t1,t2;
int rc1 = pthread_create(&t1, NULL, print_i, NULL);
int rc2 = pthread_create(&t2, NULL, print_j, NULL);
exit(0);
}
The keyword void (not a pointer) means "nothing" in C. This is consistent.
As you noted, void* means "pointer to anything" in languages that support raw pointers (C and C++). This means you need to return something.
This is the reason why you get this type of warning.
If you return someting, like return 0; warnings disapear.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
// These two functions will run concurrently
void* print_i(void *ptr)
{
printf("I am in i\n");
return 0;
}
void* print_j(void *ptr)
{
printf("I am in j\n");
return 0;
}
int main()
{
pthread_t t1,t2;
int rc1 = pthread_create(&t1, NULL, print_i, NULL);
int rc2 = pthread_create(&t2, NULL, print_j, NULL);
exit(0);
}
You can learn more about it here:
https://linux.die.net/man/3/pthread_create

How to get a pthread name in C

Say I create a pthread as pthread_t lift_3; and pthread_create(&lift_1, NULL, lift, share);. When it goes into lift(), how can I get it the function to print the actual name of the thread? Or set a name for the thread?
I have tried using pthread_self() to acquire the id, but it instead gives random numbers
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* lift(void* ptr)
{
printf("thread name = %c\n", pthread_self());
pthread_exit(NULL);
return NULL;
}
int main()
{
pthread_t lift_1; // declare thread
pthread_create(&lift_1, NULL, lift, NULL);
pthread_join(lift_1, NULL);
return 0;
}
The expected outcome should be thread name = lift_1
You're looking for the "name of the function that the thread started in".
There is no such thing as "thread name".
When calling pthread_self, you get the "id" of the thread, which something like a randomly-generated name.
To simulate the desired behavior in the past, I wrote the following code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// This lines means a variable that is created per-thread
__thread const char* thread_name;
void* lift(void* ptr)
{
// Paste this line in the beginning of every thread routine.
thread_name = __FUNCTION__;
// Note two changes in this line
printf("thread name = %s\n", thread_name);
pthread_exit(NULL);
return NULL;
}
int main()
{
// Added line
thread_name = __FUNCTION__;
pthread_t lift_1; // declare thread
pthread_create(&lift_1, NULL, lift, NULL);
pthread_join(lift_1, NULL);
//Added line
printf("Original thread name: %s\n", thread_name);
return 0;
}

In C, how do I pass variables to functions in Pthreads upon thread creation?

Working from this example:
https://computing.llnl.gov/tutorials/pthreads/samples/hello.c
I've worked backwards and tried to edit in what I'm hoping to accomplish.
I'd like to pass data to the thread being spawned.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
long NUM_THREADS=0;
void *Entropy(void *depth)
{
long tid;
tid = (long)depth;
printf("This is where things get done.\n", tid);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
NUM_THREADS = sysconf(_SC_NPROCESSORS_ONLN);
printf("Cores: %i\n", NUM_THREADS);
pthread_t threads[NUM_THREADS];
int rc;
long t;
int depth;
depth = atoi(argv[1]);
for(t=0;t<NUM_THREADS;t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, Entropy(depth), (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
I see on line:
rc = pthread_create(&threads[t], NULL, Entropy(depth), (void *)t);
My function Entropy gets called here, so I thought I'd try to tack on some brackets and pass a variable to that function the way I'd seen it done before. This seems to be a little different though, since this whole line returns something to rc, I wonder if that changes how I pass data to my thread, but I'm not sure how else I'd do it.
Right now this code compiles and runs, int main() goes fine without a hitch but it seg faults the moment it tries to create new threads.
In order to pass data to a thread you need to prepare the data in some place in memory, and pass a pointer to that place into pthread_create. It is pthread_create's job to pass that pointer to the runner function of your thread:
typedef struct {
long tid;
int depth;
}thread_data;
...
void *Entropy(void *dataPtr) {
thread_data *data= (thread_data*)dataPtr;
printf("This is where things get done for %li.\n", data->tid);
pthread_exit(NULL);
}
...
pthread_t threads[NUM_THREADS];
thread_data data[NUM_THREADS];
...
for(t=0;t<NUM_THREADS;t++) {
data[t].tid = t;
data[t].depth = depth;
rc = pthread_create(&threads[t], NULL, Entropy, (void *)&data[t]);
}
Your code crashes since you pass incorrect parameters:
rc = pthread_create(&threads[t], NULL, Entropy(depth), (void *)t);
// ^^^^^^^^^^^^^^
Here you should pass function pointer void *(*)(void *) but you are passing void *, and moreover value is unspecified since Entropy() has no return statement (did you turn warnings on at all?). I guess it should be like this:
rc = pthread_create(&threads[t], NULL, Entropy, (void *)t);
Next, how to pass parameter to thread routine? Technically you can use any pointer, but you should think twice about what you are passing. First of all pointed data must be valid when new thread runs. I.e. you shouldn't pass addresses of any locals except if you are sure that thread is finished when you are leaving scope of passed data - use pthread_join(new_thread) at the scope end to achieve that. Another approach is to pass pointer to data at global scope, that is surely valid at any moment. But there is one flaw - such data are visible to all threads, so you may accidentally make a mess. To avoid it - use dynamic memory - allocate data block with malloc() pass pointer to thread and free it in that thread. Latter option reduces chances to corrupt someone's else data.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
long NUM_THREADS=0;
void *Entropy(void *depth)
{
long tid = *((long *)depth);
free(depth);
printf("This is where things get done.\n", tid);
return NULL;
}
int main(int argc, char *argv[])
{
NUM_THREADS = sysconf(_SC_NPROCESSORS_ONLN);
printf("Cores: %i\n", NUM_THREADS);
pthread_t threads[NUM_THREADS];
int rc;
long t;
int depth;
depth = atoi(argv[1]);
for(t=0;t<NUM_THREADS;t++){
long *arg = malloc(sizeof(*arg));
*arg = t;
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, Entropy, arg);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
for(t=0;t<NUM_THREADS;t++){
pthread_join(threads[t], NULL);
}
}

Multithreaded Linux program not giving expected output

This is my code, I compiled it with:
gcc thread.c -lpthread
It didn't print any error or warning. But when I run it, the program doesn't print anything.
Platform: Ubuntu 11.10 64 bit gcc 4.6.1
Exit status :0
When I debug it, I found it prints hello as I expected.
This is my code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *loopPrint(void *ptr)
{
char *p = (char *)ptr;
while (1)
{
printf("%s\n", p);
}
}
void *pClock(void *ptr)
{
sleep(3);
exit(0);
}
int main()
{
pthread_t showMsg, clock;
int main_pth, wait_pth;
char *msg = "Hello";
main_pth = pthread_create(&showMsg, NULL, loopPrint, (void *)msg);
wait_pth = pthread_create(&clock, NULL, pClock, NULL);
pthread_join(main_pth, NULL);
pthread_join(wait_pth, NULL);
return 0;
}
pthread_join(main_pth, NULL);
This is wrong, pthread_join takes a pthread_t as an argument. Replace with:
pthread_join(showMsg, NULL);
(Same for the other one.)
And do check the return values of these calls, they can and do fail.
And BTW, you're missing #include <unistd.h> for the sleep call.
main_pth etc is the error return of pthread_create and not the thread id. Wait ("join") for showMsg and clock.

How to return a value from pthread threads in C?

I'am new to C and would like to play with threads a bit. I would like to return some value from a thread using pthread_exit()
My code is as follows:
#include <pthread.h>
#include <stdio.h>
void *myThread()
{
int ret = 42;
pthread_exit(&ret);
}
int main()
{
pthread_t tid;
void *status;
pthread_create(&tid, NULL, myThread, NULL);
pthread_join(tid, &status);
printf("%d\n",*(int*)status);
return 0;
}
I would expect the program output "42\n" but it outputs a random number. How can I print the returned value?
It seems to be a problem that I am returning a pointer to a local variable. What is the best practice of returning/storing variables of multiple threads? A global hash table?
Here is a correct solution. In this case tdata is allocated in the main thread, and there is a space for the thread to place its result.
#include <pthread.h>
#include <stdio.h>
typedef struct thread_data {
int a;
int b;
int result;
} thread_data;
void *myThread(void *arg)
{
thread_data *tdata=(thread_data *)arg;
int a=tdata->a;
int b=tdata->b;
int result=a+b;
tdata->result=result;
pthread_exit(NULL);
}
int main()
{
pthread_t tid;
thread_data tdata;
tdata.a=10;
tdata.b=32;
pthread_create(&tid, NULL, myThread, (void *)&tdata);
pthread_join(tid, NULL);
printf("%d + %d = %d\n", tdata.a, tdata.b, tdata.result);
return 0;
}
You are returning the address of a local variable, which no longer exists when the thread function exits. In any case, why call pthread_exit? why not simply return a value from the thread function?
void *myThread()
{
return (void *) 42;
}
and then in main:
printf("%d\n", (int)status);
If you need to return a complicated value such a structure, it's probably easiest to allocate it dynamically via malloc() and return a pointer. Of course, the code that initiated the thread will then be responsible for freeing the memory.
You've returned a pointer to a local variable. That's bad even if threads aren't involved.
The usual way to do this, when the thread that starts is the same thread that joins, would be to pass a pointer to an int, in a location managed by the caller, as the 4th parameter of pthread_create. This then becomes the (only) parameter to the thread's entry-point. You can (if you like) use the thread exit value to indicate success:
#include <pthread.h>
#include <stdio.h>
int something_worked(void) {
/* thread operation might fail, so here's a silly example */
void *p = malloc(10);
free(p);
return p ? 1 : 0;
}
void *myThread(void *result)
{
if (something_worked()) {
*((int*)result) = 42;
pthread_exit(result);
} else {
pthread_exit(0);
}
}
int main()
{
pthread_t tid;
void *status = 0;
int result;
pthread_create(&tid, NULL, myThread, &result);
pthread_join(tid, &status);
if (status != 0) {
printf("%d\n",result);
} else {
printf("thread failed\n");
}
return 0;
}
If you absolutely have to use the thread exit value for a structure, then you'll have to dynamically allocate it (and make sure that whoever joins the thread frees it). That's not ideal, though.
I think you have to store the number on heap. The int ret variable was on stack and was destructed at the end of execution of function myThread.
void *myThread()
{
int *ret = malloc(sizeof(int));
if (ret == NULL) {
// ...
}
*ret = 42;
pthread_exit(ret);
}
Don't forget to free it when you don't need it
Another solution is to return the number as value of the pointer, like Neil Butterworth suggests.
#include<stdio.h>
#include<pthread.h>
void* myprint(void *x)
{
int k = *((int *)x);
printf("\n Thread created.. value of k [%d]\n", k);
//k =11;
pthread_exit((void *)k);
}
int main()
{
pthread_t th1;
int x =5;
int *y;
pthread_create(&th1, NULL, myprint, (void*)&x);
pthread_join(th1, (void*)&y);
printf("\n Exit value is [%d]\n", y);
}
You are returning a reference to ret which is a variable on the stack.
Question : What is the best practice of returning/storing variables of multiple threads? A global hash table?
This totally depends on what you want to return and how you would use it? If you want to return only status of the thread (say whether the thread completed what it intended to do) then just use pthread_exit or use a return statement to return the value from the thread function.
But, if you want some more information which will be used for further processing then you can use global data structure. But, in that case you need to handle concurrency issues by using appropriate synchronization primitives. Or you can allocate some dynamic memory (preferrably for the structure in which you want to store the data) and send it via pthread_exit and once the thread joins, you update it in another global structure. In this way only the one main thread will update the global structure and concurrency issues are resolved. But, you need to make sure to free all the memory allocated by different threads.
if you're uncomfortable with returning addresses and have just a single variable eg. an integer value to return, you can even typecast it into (void *) before passing it, and then when you collect it in the main, again typecast it into (int). You have the value without throwing up ugly warnings.
#include <pthread.h>
#include <stdio.h>
#include <stdint.h>
void *myThread(void *args)
{
return (void *)(intptr_t)42;
}
int main(void)
{
pthread_t tid;
void *status;
int ret;
pthread_create(&tid, NULL, myThread, NULL);
ret = pthread_join(tid, &status);
if (ret) {
fprintf(stderr, "pthread_join() failed\n");
return -1;
}
/* pthread_join() copies the exit status (namely 42) of the target thread
* into the location pointed to by retval (namely &status), &status points
* to void *, so we need to cast void * to int.
*/
printf("%ld\n", (intptr_t)status);
return 0;
}

Resources