⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 spinlock.c

📁 用c++包装好的线程库,直接拿来使用,提高效率.
💻 C
字号:
//// struct spinlock//// this structure is a primitive semaphore.  It simple controls// the situation of a single integer... with an on/off value.#include "threads/spinlock.h"extern "C" {#       include <sched.h>};namespace cpp_threads {  // Initializer, just to make sure.  spinlock::spinlock()  {    s_spinlock = 0;  }  spinlock::~spinlock()  {  }  //  // testandset  //  // test if the spinlock is clear, and set it in one atomic  // instruction.  Ensuring it is owned by only one process.  int spinlock::testandset()  {    register int ret=1;#if defined(__i386__)#ifdef __SMP__#define LOCK "lock ; "#else#define LOCK#endif    __asm__ __volatile__(LOCK     			 "xchgl %0, %1"    			 : "=r"(ret), "=m"(s_spinlock)    			 : "0"(1), "m"(s_spinlock));#else#  if defined( __SPARC__ )        __asm__ __volatile__("swap [%2], %0"                             : "=&r" (ret)                             : "0" (1), "r" (&s_spinlock));#  else#   if defined( __PPC__ )        __asm__ __volatile__ ("1:      lwarx   %0,0,%2 \n"			      "        stwcx.  %3,0,%2 \n"			      "        bne-    1b"			      : "=&r" (ret), "=m" (s_spinlock)			      : "r" (&s_spinlock), "r" (1), "m" (s_spinlock)			      : "cc", "memory");#   else#    if defined( __alpha__ )	long dummy;        __asm__ __volatile__(			     "1:     ldl_l %0,%4\n"			     "       bis $31,%3,%1\n"			     "       stl_c %1,%2\n"			     "       beq %1,2f\n"#ifdef __SMP__			     "       mb\n"#endif			     ".subsection 2\n"			     "2:     br 1b\n"			     ".previous"			     : "=&r" (ret), "=&r" (dummy), "=m" (s_spinlock)			     : "rI" (1), "m" (s_spinlock) : "memory");#    else#      warning "FIXME: This CPU needs inlined assembly"	register __volatile__ int& refp = s_spinlock;	if( refp++ == 0 )	  ret  = 0;	else	  refp--;#    endif#   endif#  endif#endif    return ret;  }  //  // acquire  //  // continue to try and set the spinlock, until successfull.  Yielding  // to other processes in the scheduling while waiting.  void spinlock::acquire()  {    do {      sched_yield();    } while (testandset());  }  //  // release  //  // release the spinlock, by setting it to 0.  void spinlock::release()  {    s_spinlock = 0;  }}; // namespace

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -