Thomas Darimont
Erfahrenes Mitglied
Hallo,
hier mal ein kleines Beispiel zu multi-threading mit PThreads in C als DevCPP Projekt.
Als PThread Implementierung habe ich PThread-win32 verwendet:
http://sourceware.org/pthreads-win32/
main.c
Ausgabe:
Gruß Tom
hier mal ein kleines Beispiel zu multi-threading mit PThreads in C als DevCPP Projekt.
Als PThread Implementierung habe ich PThread-win32 verwendet:
http://sourceware.org/pthreads-win32/
main.c
C:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
/*
* function do_something wird mit der entsprechenden Thread ID als Parameter von den erzeugten Threads aufgerufen
*/
void *do_something(void *arg){
int *args = ((int*)arg);
printf("hallo welt from thread %d!\n", args[0]);
int i;
for(i = 0; i < 100; i++){
printf("Thread(%d) sleep: %d num: %d\n" ,args[0],args[1], i );
sleep(args[1]);
}
return NULL;
}
int main(int argc, char *argv[])
{
int status;
pthread_t thread1;
int thread1_args[2];
thread1_args[0]=1; //Thread ID des ersten Threads
thread1_args[1]=250; //sleep in Millisekunden innerhalb jeder Schleifeniteration in do_something(..)
//Thread 1 starten
status = pthread_create(&thread1, NULL, do_something, &thread1_args);
if(status != 0){
printf("Error creating thread1!\n");
}else{
printf("thread1 started\n");
}
pthread_t thread2;
int thread2_args[2];
thread2_args[0]=2; //Thread ID des zweiten Threads
thread2_args[1]=100; //sleep in Millisekunden innerhalb jeder Schleifeniteration in do_something(..)
//Thread 2 starten
status = pthread_create(&thread2, NULL, do_something, &thread2_args);
if(status != 0){
printf("Error creating thread2!\n");
}else{
printf("thread2 started\n");
}
//Auf Beendigung von Thread 1 warten
status = pthread_join(thread1,NULL);
if(status != 0){
printf("Error joining thread1!\n");
}else{
printf("thread1 joined\n");
}
//Auf Beendigung von Thread 2 warten
status = pthread_join(thread2,NULL);
if(status != 0){
printf("Error joining thread2!\n");
}else{
printf("thread2 joined\n");
}
system("PAUSE");
return 0;
}
Ausgabe:
Code:
thread1 started
thread2 started
hallo welt from thread 1!
Thread(1) sleep: 250 num: 0
hallo welt from thread 2!
Thread(2) sleep: 100 num: 0
Thread(2) sleep: 100 num: 1
Thread(2) sleep: 100 num: 2
Thread(1) sleep: 250 num: 1
Thread(2) sleep: 100 num: 3
Thread(2) sleep: 100 num: 4
Thread(1) sleep: 250 num: 2
Thread(2) sleep: 100 num: 5
Thread(2) sleep: 100 num: 6
Thread(2) sleep: 100 num: 7
Thread(1) sleep: 250 num: 3
....
Gruß Tom