---
title: "nth4"
author: "mmdev"
date: "2011-12-19T20:54:00Z"
tags: []
slug: "nth4"
draft: false
lastmod: "2012-07-23T23:49:00Z"
id: 1604805
url: "https://mmdev.iteye.com/blog/1604805"
---

#include &lt;stdlib.h&gt;  
#include &lt;stdio.h&gt;  
#include &lt;pthread.h&gt;

int thread\_num = 1;  
long vector\_length = 100000;  
int total = 0;  
int \*a = NULL;

void \*vel\_mul(void \*arg);

int main(int argc, char \*argv\[]){  
int res;  
void \*thread\_result;  
//scan income  
if(argc != 3){  
printf("You have not enter enough parameters. So using default parameter\\n");  
}  
else{  
thread\_num = atoi(argv\[1]);  
vector\_length = atol(argv\[2]);  
}  
printf("Thread number is %d. Vector length is %ld\\n",thread\_num,vector\_length);  
//scan finished

//start create threads  
a = (int \*)calloc(vector\_length,sizeof(int));  
for(int i = 0; i &lt; vector\_length; i++){  
switch((i+1)%3){  
case 0 :  
a\[i]=1;  
break;  
case 1 :  
a\[i]=-1;  
break;  
case 2 :  
a\[i]=0;  
break;  
}  
}  
pthread\_t \*a\_thread;  
a\_thread = (pthread\_t \*)calloc(thread\_num,sizeof(pthread\_t));

for(int i = 0; i &lt; thread\_num; i++){  
res = pthread\_create(&a\_thread\[i],NULL,vel\_mul,(void \*)&i);  
if(res != 0)perror("thread creation failed");  
}

printf("Waiting ...\\n");

for(int i = thread\_num-1; i &gt;=0; i--){  
res = pthread\_join(a\_thread\[i],&thread\_result);  
}  
printf("finish \\n");  
printf("total is %d\\n",total);