To bind a CPU to a thread

Source: Internet
Author: User

Learn gcc atomic variable#define _gnu_source#include <stdio.h> #include <stdlib.h> #include <unistd.h > #include <pthread.h> #include <sys/syscall.h> #include <linux/unistd.h> #include <errno.h > #include <sched.h> #define INC_TO 1000000//Every thread adds 1 million timesint global_int = 0;//Get current T    Hread idpid_t Gettid (void) {return syscall (__nr_gettid); return pthread_self (); Cannot work ...}    void *thread_routine (void *arg) {int i;    int proc_num = (int) (long) (ARG); cpu_set_t set;    A CPU Affinity Mask Cpu_zero (&set);    Cpu_set (Proc_num, &set);    ETS the CPU affinity mask of this thread to the value specified by Maski.    A thread ' s CPU affinity mask determines the set of CPUs on which it's eligible to run.        if (Sched_setaffinity (Gettid (), sizeof (cpu_set_t), &set)) {perror ("sched_setaffinity");    return NULL;        } for (i = 0; i < inc_to; i++) {//global_int + +; __sYnc_fetch_and_add (&global_int, 1); } return NULL;    int main () {int procs = 0;    int i;    pthread_t *threads;    Get the number of processors currently online (available).   procs = (int) sysconf (_SC_NPROCESSORS_ONLN);        Mine is + if (Procs < 0) {perror ("sysconf");    return-1;    } threads = malloc (sizeof (pthread_t) * procs);        if (threads = = NULL) {perror ("malloc threads");    return-1;    } printf ("Set up%d threads ... \ n", procs);            for (i = 0; i < procs; i++) {if (Pthread_create (&threads[i], NULL, Thread_routine, (void *) (long) i)) {            Perror ("Pthread_create");            procs = i;        Break    }} for (i = 0; i < procs; i++) {Pthread_join (threads[i], NULL);    } free (threads);    printf ("All Threads-Done.global_int is%d\n", global_int);    printf ("The expected value is%d\n", inc_to * procs); return 0;}


Reference: Http://www.alexonlinux.com/multithreaded-simple-data-type-access-and-atomic-variables

To bind a CPU to a thread

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.