0

I am having some problems with outputing my threads in a right order. My program needs to take at least 2 parameters (could be more, but always 2 at a time because one is integer(how many second does the thread wait) and the other is char*(just a regular message)). Output of the program is the thread number(index) and the message from the second parameter, but the threads need to be sorted based on the time they had from the first parameter. The main thread needs to wait for all the other threads. There will be a maximum of 10 threads.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>


void* thread_main(void* arg){
    sleep(1);
    return NULL;
}

int main(int argc, char** argv){
    pthread_t tid[10];
    int s;

    int index=0;
    for(int i=1;i<argc;i+=2){
      int param1= atoi(argv[i]);
      char* param2= argv[i+1];

      s=pthread_create(&tid[index],NULL,thread_main,NULL);
      usleep(param1*1000);
      printf("Thread %d : %s\n",index+1,param2);
      index++;
    }
    
    for(int i=0;i<index+1;i++){
      s=pthread_join(tid[i],NULL);
    }    
    
    return 0;
}

This is my code. When I enter the parameters for the code:

300 this_is_last 100 this_is_first 200 this_is_middle

Output should be like this:

Thread 2 : this_is_first
Thread 3 : this_is_middle
Thread 1 : this_is_last

But with my code I get this:

Thread 1 : this_is_last
Thread 2 : this_is_first
Thread 3 : this_is_middle

I am new to threads and I really do not know how to fix this.

  • 1
    I don't get what your problem is, and what relation does it have with threads. Why should your loop print the command line arguments ("this_is_last", etc) in another order than that in which they were supplied? – mosvy Apr 5 at 15:32
  • 1
    Also, you have an off-by-one bug in the pthread_join() loop. – mosvy Apr 5 at 15:36
0

From looking at the code. There is no output within the threads. Therefore the threading does nothing. You can remove the create_thread, and it will do exactly the same thing.

The output will be in sequential order. With varying times (according to the even parameters).

Also every thread is called thread_main.

What to do.

Put the varying delay, and the printf in thread_main. (And give it a better name). You Then have to pass the message, and the id, to the thread.

See manual for an example of how to do it. Note tinfo being passed to the thread.

I would start by having 3 routines, one for each thread, with different messages and IDs. When this is working start exploring how to pass information to them at start up.

| improve this answer | |
  • I added delays and printf to threads and added structs to pass value . Now it works. Thanks for the help. – dontknowhowtocode123 Apr 5 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.