SHARE
TWEET

Untitled

a guest Jan 19th, 2020 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <thread>
  2. #include <stdio.h>
  3. #include <memory.h>
  4.  
  5. // compile with g++ cachetear.cpp -lpthread -O2 -g -o cachetear
  6. // spams without optimization
  7.  
  8. // 64 byte cache lines, tear should cross the line
  9. //#pragma pack(0)  // for MSVC
  10.  
  11. struct __attribute__((packed)) CTest
  12. {
  13.     char padding[62];
  14.     unsigned int tear;
  15. };
  16.  
  17. int main(void)
  18. {
  19.     CTest test;
  20.     memset(&test, 0, sizeof(test));
  21.  
  22.     const int testVal1 = 0xABABABAB;
  23.     const int testVal2 = 0xCDCDCDCD;
  24.  
  25.     auto test1 = [&test]()
  26.     {
  27.         while(1)
  28.         {
  29.             test.tear = testVal1;
  30.         }
  31.     };
  32.  
  33.     auto test2 = [&test]()
  34.     {
  35.         while(1)
  36.         {
  37.             test.tear = testVal2;
  38.         }
  39.     };
  40.  
  41.     std::thread t1(test1);
  42.     std::thread t2(test2);
  43.  
  44.     printf("Setting up threads...\n");
  45.  
  46.     while(1)
  47.     {
  48.         if(!(test.tear == testVal1 || test.tear == testVal2))
  49.         {
  50.             printf("Got torn val: 0x%X\n", test.tear);
  51.         }
  52.     }
  53.    
  54. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top