博客年龄:17年6个月
访问:?
文章:291篇

个人描述

姓名:丹臣 职业:DBA 公司:TAOBAO Mail:zhaolinjnu(at)163.com MSN:echo_lin@hotmail.com 微博http://twitter.com/zhaolinjnu

muti-thread与mutex实践

分类:Linux | 标签: mutex   lock   unlock   zhaolinjnu  
2011-03-07 10:47 阅读(?)评论(0)

上周写了一个测试程序,在多线程模式下,使用mutex, 操作一个共享资源,看看争用情况怎么样?创建的线程越多(>100),争用会相当明显;几个线程(<10),看不出来.

#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#define MAX_THREADS 1024

//global variables
pthread_t thread[MAX_THREADS];
struct thd_status_t
{
  int thread_id;
  int status;
};
struct thd_status_t thd_status[MAX_THREADS];
pthread_mutex_t mut;
int num=0;


void *thread_do()
{
  int h,elapsed;
  time_t begin,tmp_time;
  int mythreadid=pthread_self();

  begin=tmp_time=time(NULL);
  for(h=0;h<6;h++)
  {
     pthread_mutex_lock(&mut);
     printf("thread number is %d.\n",mythreadid);
     num++;
     printf("h=%d,num=%d\n",h,num);
     while(1!=0)
     {
        if(time(NULL)-tmp_time>2)
           {
              tmp_time=time(NULL);
              break;
           }
     }
     pthread_mutex_unlock(&mut);
  }  

  //exit
  elapsed=time(NULL)-begin;
  printf("thread %d :running time -> %ld elapsed.\n",mythreadid,time(NULL)-begin);
  pthread_exit(NULL);
}

void create_thread(int n_threads)
{
  int j;
  //what memset do
  if(n_threads>MAX_THREADS) return;
 
  memset(&thread,0,sizeof(thread));
  for(j=0;j<n_threads;j++)
     if(pthread_create(&thread[j],NULL,thread_do,NULL)==0)
       {
          printf("create thread[%d] sucess.\n",j);
       }
     else
       {
          printf("create failure.\n");
       }
}

void stop_thread(int n_threads)
{
   int k;
   for(k=0;k<n_threads;k++)
     if(thread[k]!=0)
         pthread_join(thread[k],NULL);
}

int main(int argc,char **argv)
{
   printf("input N threads you wait to create:\n");
   printf(">");
   int n;
   scanf("%d",&n);
   pthread_mutex_init(&mut,NULL);
   if(n>0) create_thread(n);
   printf("I am main threads.\n");
   stop_thread(n);
   return 0;
}

编译的方法:

gcc -g -o muti_thread muti_thread.c -lpthread

  最后修改于 2011-03-07 10:54    阅读(?)评论(0)
上一篇: 该日志被锁定 下一篇:该日志被锁定
 
表  情:
加载中...
 

请各位遵纪守法并注意语言文明