Arguments were passed wrong in pthread

I write a code to print out strings: "Thread 0" to "Thread 4" using pthread.

Here is my code:

Case 1:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *print_message_function(void* parameter) {
    long *i = (long *)parameter;
    printf("Thread %ld\n", *i);
    pthread_exit(0);
}

int main(int argc, char *argv[]) {
    pthread_t threads[5];
    long i = 0;
    for (i = 0; i < 5; i++) {
        pthread_create(&threads[i], 0, print_message_function, (void *)&i);
    }

    pthread_exit(NULL);
}

But the result is:

Thread 2
Thread 3
Thread 3
Thread 4
Thread 5

or:

Thread 0
Thread 0
Thread 0
Thread 0
Thread 0

It changed when I run it again. So I don't know why the values I passed are (2 to 5) or all (0) or ..... (many cases). I think my arguments I passed is from 0 to 4.

Case 2:

When I change to the new code:

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

void *print_message_function(void *parameter);

int main(int argc, char *argv[]) {
    pthread_t threads[5];
    int i = 0;
    for (i = 0; i < 5; i++) {
        char *msg = (char*)malloc(sizeof(char));
        sprintf(msg, "Thread %d", i);
        pthread_create(&threads[i], 0, print_message_function, (void *)msg);
    }
}

void *print_message_function(void *parameter) {
    printf("%s\n", (char *)parameter);
}

The result is:

Thread 1
Thread 0
Thread 3
Thread 2
Thread 4
Thread 4

It means the loop run 6 times! Why?

Answers


Change Case 1 to this:

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

void *print_message_function(void* parameter) {
    long i = (long)parameter;  // <<<
    printf("Thread %ld\n", i); // <<<
    pthread_exit(0);
}

int main(int argc, char *argv[]) {
    pthread_t threads[5];
    long i = 0;
    for (i = 0; i < 5; i++) {
        pthread_create(&threads[i], 0, print_message_function, (void *)i); // <<<
    }

    pthread_exit(NULL);
}

The reason that you were seeing inconsistent results before was because you were passing a pointer to each thread where each pointer was pointing at the same local variable, which you were then modifying.

In Case 2 you are mallocing only a single char and then trying to write a string to it. It should be fairly easy to fix.


Need Your Help

CAKEPHP Stucked in Associating Models

php cakephp model

Im using cakephp and Im stuck about the idea of listing multiple models, here's my scenario:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.