Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <stdint.h>
- #include <inttypes.h>
- typedef struct neco{
- int *pole;
- int local_konec;
- int64_t soucet;
- pthread_t thr_id;
- }STRUCT;
- void *thrFunc ( void *arg ){
- STRUCT *data = (STRUCT *)arg;
- int *i;
- for (i=data->pole; i!=data->pole + data->local_konec; i++ ){
- data->soucet+=*i;
- }
- return NULL;
- }
- void napln_pole(int *pole, int velikost){
- int i;
- for(i=0; i<velikost; i++)
- *(pole+i) = i % 10;
- }
- void napln_strukturu(STRUCT *structure, int velikost, int poc_vlaken, int *pole){
- int i, dil;
- dil = velikost / poc_vlaken;
- for(i=0; i<poc_vlaken; i++){
- structure[i].pole = pole+i*dil;
- structure[i].soucet = 0;
- structure[i].local_konec =dil;
- }
- structure[poc_vlaken-1].local_konec += velikost % poc_vlaken;
- }
- void vypis(int poc_vlaken, STRUCT *structure){
- int64_t soucet;
- int i;
- soucet=0;
- for(i = 0; i<poc_vlaken; i++)
- soucet+=structure[i].soucet;
- printf("VYSLEDEK%" PRId64 "\n", soucet);
- }
- int main( int argc, char * argv []){
- int velikost, poc_vlaken,i;
- STRUCT *structure;
- pthread_attr_t thrAttr;
- int *pole;
- void *dummy;
- if( argc != 3 || sscanf(argv[1], "%d", &velikost) !=1
- || sscanf(argv[2], "%d", &poc_vlaken) !=1){
- printf("Neplatny vstup! Zadej: ./%s pocetPrvku pocetVlaken", argv[0]);
- return 1;
- }
- pole = (int*)malloc(velikost*sizeof(*pole));
- structure = (STRUCT*)malloc(poc_vlaken*sizeof(*structure));
- napln_pole( pole, velikost );
- napln_strukturu(structure, velikost, poc_vlaken, pole);
- pthread_attr_init ( &thrAttr );
- pthread_attr_setdetachstate ( &thrAttr, PTHREAD_CREATE_JOINABLE );
- for(i=0; i<poc_vlaken; i++)
- if( pthread_create(&structure[i].thr_id, &thrAttr, thrFunc, &structure[i])){
- free ( structure );
- perror ( "Create thread\n" );
- pthread_attr_destroy ( &thrAttr );
- return ( 1 );
- }
- pthread_attr_destroy ( &thrAttr );
- for ( i = 0; i < poc_vlaken; i ++ )
- pthread_join ( structure[i].thr_id, &dummy );
- vypis(poc_vlaken, structure);
- free ( structure );
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement