SO:PlusMinus

Z Wiki Rafał (ert16) Trójniak

#include <iostream>
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
using namespace std;
 
// Tablica znaków wypisywanych przez kolejne wątki
char ticks[] = { '+','-','.','*','@' };
 
// Struktura informacyjna o wątkach
struct thread_info {    /* Used as argument to thread_start() */
	pthread_t thread_id;        /* ID returned by pthread_create() */
	int       thread_num;       /* Application-defined thread # */
	char     *argv_string;      /* From command-line argument */
};
 
 
// Funkcja wątku , wypisuje znak wskazywany jako argument 
static void * thread_start(void *arg)
{
	char c = *((char* ) arg);
	for(unsigned l=0;l<1000;l++)
	cout<<c;
	return NULL;
}
 
int main(int argc, char *argv[])
{
	pthread_attr_t attr;
	pthread_t * threads;
 
	// Ilość uruchamianych wątków
	unsigned thread_cnt = 2;
	threads = new pthread_t[thread_cnt ];
 
	// Inicjalizacja wątków
	pthread_attr_init( &attr );
	for(unsigned i=0;i<thread_cnt ;i++)
	{
		// Startujemy wątki
		pthread_create(   threas + i  , &attr, &thread_start, &ticks[ i ] );
	}
	pthread_attr_destroy(&attr);
 
	// Czekamy na zakończenia wątków
	for(unsigned i=0;i<thread_cnt ;i++)
		pthread_join(threads[i], NULL);
	// Aby ładnie wyglądało na konsoli
	cout << endl;
 
}
Osobiste