I need to do the following:
Create a thread that creates 10 threads in a row.
Each thread just prints it's ID and sleeps for n seconds, where n is the serial number of current thread.
But, I can't get passing arguments right, when I run my code it seems like the thread is just sleeping.. Some help, please?
Here is my code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
# define N 10
void* printID (void *i)
{
int* p=(int*) i;
sleep(p);
pthread_exit(NULL);
}
void* th (void* unused)
{
int sec,i;
sec=1;
i=1;
while(i<=10){
pthread_t pid1;
pthread_create (&pid1, NULL, &printID, (void *)&i);
pthread_join(pid1,NULL);
printf("Thread ID je: %d \n",(int) pid1);
i=i+1;
}
}
int main(){
pthread_t pid;
pthread_create (&pid, NULL, &th, NULL);
pthread_join(pid,NULL);
return 0;
}
Your argument passing is fine. But you are not passing the value to sleep.
It should be
sleep(*p);
p points the address of i (from the function th()). You need to dereference the pointer to get the value.
Related
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);
}
}
I have a range of number (i.e 1~10000).
I need to create threads to search for a value X.
Each thread will have your own interval to search for it (i.e 10000/threadNumber).
I guess there is no meaning to make the threads run in sequence. I'm having problem to make they run concurrently...
My Code so far:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define limit 10000
#define n_threads 2
void* func1(void* arg)
{
int i=0, *value = (int *)arg;
//How may I know which thread is running and make the thread search for the right range of values ?
for(i=1; i<=limit/n_threads; i++)
{
if(*value == i){
//Print the thread ID and the value found.
}
else
//Print the thread ID and the value 0.
}
return NULL;
}
int main(int argc, char const *argv[])
{
if(argc < 2)
printf("Please, informe the value you want to search...\n");
else{
pthread_t t1, t2;
int x = atoi(argv[1]); //Value to search
pthread_create(&t1, NULL, func1, (void *)(&x));
pthread_create(&t2, NULL, func1, (void *)(&x));
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}
return 0;
}
Problems so far:
I don't know how to find thread ID. (tried with pthread_self() but I always get a giant negaative number so I think something is wrong.
I know that pthread_create() creates and initialize the thread, also the pthread_join will make my main program to wait for the thread. But Looking into my code it doesn't seems to be runing concurrently.
How my threadX will know from what range of values it's suppose to start searching ? (i.e: If I have 10 threads, I don't think I'll have to create 10 functions o.O ).
is it possible to make them run concurrently without something like Mutex ?
Getting the thread id varies according to your operating system.
See how to get thread id of a pthread in linux c program? as #user3078414 mentioned, and why compiler says ‘pthread_getthreadid_np’ was not declared in this scope?.
Credits to #Dmitri, an example of passing multiple values to the thread function. The threads run concurrently. Mutexes is a whole other chapter that deals with shared data and how you access it.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define limit 10000
#define n_threads 2
struct targs {
int from;
int to;
};
void *func1(void *arg) {
struct targs *args = (struct targs *) arg;
printf("%d => %d\n", args->from, args->to);
// free(arg)
return NULL;
}
int main(int argc, char const *argv[]) {
struct targs *args;
pthread_t t1;
pthread_t t2;
args = (struct targs *) malloc(sizeof(args));
args->from = 0;
args->to = 100;
pthread_create(&t1, NULL, func1, (void *) args);
args = (struct targs *) malloc(sizeof(args));
args->from = 100;
args->to = 200;
pthread_create(&t2, NULL, func1, (void *) args);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
The code is sample, what I need to do is to modify.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *my_function (void*); // Function for the thread
int main ()
{
pthread_t my_thread ; // Declare a thread identifier
int rc1, x = 7;
// Create my_thread
if ( (rc1 = pthread_create (& my_thread, NULL, & my_function, (void*) &x)))
{
printf ("Error in creating thread %d\n", rc1);
}
pthread_join ( my_thread, NULL); // wait for thread to exit
return (0); // exit the main function
}
// The my_thread is created with my_function() which accepts an argument
void *my_function(void* arg)
{
int i = *(int*)arg;
printf ("The argument which this thread received is %d \n", i ) ;
pthread_exit (NULL) ; // thread exits
}
The question is: Pass a simple integer to a thread’s start function at thread creation time. But I don't know how to pass a simple integer to a thread's start function, and I also don't know what is thread creation time.
If your imlementation has intptr_t (most of them do), you can modify the code as following:
int rc1;
intptr_t x = 7
...
pthread_create (&my_thread, NULL, &my_function, (void*)x));
...
void* my_function(void* arg)
{
intptr_t i = (intptr_t)arg;
...
I'm experimenting with pthreads and for the following code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* print_thread_num(void *index);
int main(int argc, char** argv) {
int i;
pthread_t threads[3];
for (i = 0; i < 3; i++) {
void *index = &i;
printf("Creating thread %d\n", i);
pthread_create(&threads[i], NULL, print_thread_num, index);
}
pthread_exit(NULL);
}
void* print_thread_num(void *index) {
int i = *(int*)index;
printf("I am the thread at index %d\n", i);
pthread_exit(NULL);
}
I'm getting the output below:
Creating thread 0
Creating thread 1
I am the thread at index 1
Creating thread 2
I am the thread at index 2
I am the thread at index 3
Why is each "I am the thread at index" printing an index higher than what it should print?
You're passing the address of your loop variable i, this is being incremented in the main thread while your child threads access it.
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;
}