一个多线程绑定到不同cpu上的例子

01 #include <stdio.h>
02 #include <pthread.h>
03 #include <unistd.h>
04 #include <stdlib.h>
05 #include <sched.h>
06 #include <linux/unistd.h>
07 #include <sys/syscall.h>
08 #include <errno.h>
09  
10 #define INC_TO 1000000 // one million...
11  
12 int global_int = 0;
13  
14 pid_t gettid( void )
15 {
16     return syscall( __NR_gettid );
17 }
18  
19 void *thread_routine( void *arg )
20 {
21     int i;
22     int proc_num = (int)(long)arg;
23     cpu_set_t set;
24  
25     CPU_ZERO( &set );
26     CPU_SET( proc_num, &set );
27  
28     if (sched_setaffinity( gettid(), sizeof( cpu_set_t ), &set ))
29     {
30         perror"sched_setaffinity" );
31         return NULL;
32     }
33  
34     for (i = 0; i < INC_TO; i++)
35     {
36 //      global_int++;
37         __sync_fetch_and_add( &global_int, 1 );
38     }
39  
40     return NULL;
41 }
42  
43 int main()
44 {
45     int procs = 0;
46     int i;
47     pthread_t *thrs;
48  
49     // Getting number of CPUs
50     procs = (int)sysconf( _SC_NPROCESSORS_ONLN );
51     if (procs < 0)
52     {
53         perror"sysconf" );
54         return -1;
55     }
56  
57     thrs = mallocsizeof( pthread_t ) * procs );
58     if (thrs == NULL)
59     {
60         perror"malloc" );
61         return -1;
62     }
63  
64     printf"Starting %d threads...\n", procs );
65  
66     for (i = 0; i < procs; i++)
67     {
68         if (pthread_create( &thrs[i], NULL, thread_routine,
69             (void *)(long)i ))
70         {
71             perror"pthread_create" );
72             procs = i;
73             break;
74         }
75     }
76  
77     for (i = 0; i < procs; i++)
78         pthread_join( thrs[i], NULL );
79  
80     free( thrs );
81  
82     printf"After doing all the math, global_int value is: %d\n",
83         global_int );
84     printf"Expected value is: %d\n", INC_TO * procs );
85  
86     return 0;
87 }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值