线程绑定

Posted Andy.gbhu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程绑定相关的知识,希望对你有一定的参考价值。

#include<unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include<pthread.h>
#include <sched.h>

#include<iostream>

using namespace std;

typedef struct {
  pthread_spinlock_t spinlock;
  int count;
}ThdArgs ;

void * thd_func(void *arg){
 
  while(true){
    pthread_spinlock_t *spinlock = (pthread_spinlock_t*)arg;
    pthread_spin_lock(spinlock);
    int a = 1;
    sleep(5);
    pthread_spin_unlock(spinlock);
   
    int count = 1;
    ;
  }

  return (void*)0 ;


}


void * thd_func1(void *arg){
 
  while(true){
    ThdArgs *args = (ThdArgs*)arg;
    pthread_spin_lock(&args->spinlock);

    if (10 == args->count){
      pthread_spin_unlock(&args->spinlock);
      return (void*)0;
    }
   
    cerr<<"Thread["<<pthread_self()<<"], count="<<args->count<<endl;
    args->count +=1 ;

    sleep(5);   

    if ( 10== args->count){
      pthread_spin_unlock(&args->spinlock);
      return (void*)1;
   
    }
    else
      pthread_spin_unlock(&args->spinlock);
  }

  return (void*)0 ;


}

 

int createBindThread(pthread_t *pthd, int cpuSeq, void * (*func)(void *), void *arg ){

  pthread_attr_t attr1;
  pthread_attr_init(&attr1);

  cpu_set_t cpuset;
  CPU_ZERO(&cpuset);
  CPU_SET(cpuSeq, &cpuset);


  if( pthread_attr_setaffinity_np(&attr1, sizeof(cpuset), &cpuset) ){
    cerr<<"setaffinity error "<<endl;
    return -1;

  }

  if ( pthread_create(pthd, &attr1, func, arg) ){
    cerr<<"pthread_create error "<<endl;
    return -1;
  }
  


  return 0;
}


int main(){

  int cpuCount = (int)sysconf(_SC_NPROCESSORS_ONLN);
  cout<<"cpu count="<<cpuCount<<endl;

  sched_param schedParam;
  schedParam.sched_priority = 1;

  if (sched_setscheduler(getpid(), SCHED_FIFO, &schedParam) == -1){
    cerr<<"sched_setscheduler error:"<<strerror(errno)<<endl;
  }

  pthread_t thd1, thd2;

  /*

  pthread_spinlock_t spinlock;
  pthread_spin_init(&spinlock, PTHREAD_PROCESS_PRIVATE);

  createBindThread(&thd1, 0, thd_func, (void*)&spinlock);
  createBindThread(&thd2, 1, thd_func, (void*)&spinlock);
  */

  ThdArgs args;
  args.count = 0;
  pthread_spin_init(&args.spinlock, PTHREAD_PROCESS_PRIVATE);
   
  createBindThread(&thd1, 0, thd_func1, (void*)&args);
  createBindThread(&thd2, 1, thd_func1, (void*)&args);

  /*
  while(true){
    int a = 1;
  }

  */

  void *rslt1 = NULL;
  void *rslt2 = NULL;

  pthread_join(thd1, &rslt1);
  pthread_join(thd2, &rslt2);

  cout<<"test over, thread["<<thd1<<"]  return"<<rslt1<<", thread["<<thd2<<"] return"<<rslt2<<endl;

  return 0;

}

以上是关于线程绑定的主要内容,如果未能解决你的问题,请参考以下文章

为啥c ++中线程构造函数和绑定的函数签名相同[关闭]

session和线程绑定

为啥openmp不根据手动NUMA绑定放置线程?

Qt 设置CPU亲缘性,把进程和线程绑定到CPU核心上(Linux)

NSArrayController 绑定到核心数据可以在后台线程中运行获取吗?

守护线程(如果你想要绑定,主线程结束,子线程也结束可以用守护线程)