Skip to content
Snippets Groups Projects
lec1b.ipynb 7.29 KiB
Newer Older
TYLER CARAZA-HARTER's avatar
TYLER CARAZA-HARTER committed
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3b8d1ed9-9568-473e-bfa2-3b08f9e4587f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import threading\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "da885575-cedf-4bb4-8bbd-44400974d3f8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  0           RESUME                   0\n",
      "\n",
      "  1           LOAD_NAME                0 (total)\n",
      "              LOAD_CONST               0 (1)\n",
      "              BINARY_OP               13 (+=)\n",
      "              STORE_NAME               0 (total)\n",
      "              RETURN_CONST             1 (None)\n"
     ]
    }
   ],
   "source": [
    "import dis\n",
    "dis.dis(\"total += 1\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ceeb7904-ff2c-424c-bf7c-724d1b285e3b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 133 ms, sys: 144 μs, total: 133 ms\n",
      "Wall time: 129 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "2000000"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "# 133 ms with no locks\n",
    "# 348 ms with locks (fine grained)\n",
    "# 124 ms with locks (coarse grained)\n",
    "\n",
    "lock = threading.Lock() # this protects the \"total\" variable\n",
    "total = 0\n",
    "\n",
    "def task(count):\n",
    "    global total\n",
    "    lock.acquire()\n",
    "    for i in range(count):\n",
    "        total += 1\n",
    "    lock.release()\n",
    "\n",
    "t1 = threading.Thread(target=task, args=[1_000_000])\n",
    "t1.start()\n",
    "\n",
    "t2 = threading.Thread(target=task, args=[1_000_000])\n",
    "t2.start()\n",
    "\n",
    "t1.join()\n",
    "t2.join()\n",
    "\n",
    "total"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "042356c8-7d34-4fa5-bef1-0c43e829fc13",
   "metadata": {},
   "outputs": [],
   "source": [
    "import threading\n",
    "\n",
    "bank_accounts = {\"x\": 25, \"y\": 100, \"z\": 200} # in dollars\n",
    "lock = threading.Lock() # protects bank_accounts\n",
    "\n",
    "def transfer(src, dst, amount):\n",
    "    with lock: # automatically acquire now, and release after the with statement\n",
    "        success = False\n",
    "        if bank_accounts[src] >= amount:\n",
    "            bank_accounts[src] -= amount\n",
    "            bank_accounts[dst] += amount\n",
    "            success = True\n",
    "        print(\"transferred\" if success else \"denied\")\n",
    "        print(\"locked inside with?\", lock.locked())\n",
    "    print(\"locked after with?\", lock.locked())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1878620a-553b-4f25-9606-1e2605b318ac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "transferred\n",
      "locked inside with? True\n",
      "locked after with? False\n"
     ]
    }
   ],
   "source": [
    "transfer(\"x\", \"y\", 20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8901ec24-7471-40e1-8182-585d3cc760c7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'x': 5, 'y': 120, 'z': 200}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bank_accounts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9cee2370-0f3d-4ac0-930a-c59f9f0d7f1b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "denied\n",
      "locked inside with? True\n",
      "locked after with? False\n"
     ]
    }
   ],
   "source": [
    "transfer(\"x\", \"z\", 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3a583c7c-57a3-4f42-8301-8ce601a2249e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'x': 5, 'y': 120, 'z': 200}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bank_accounts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3346b86d-5f80-4007-8879-b452c4826c50",
   "metadata": {},
   "outputs": [
    {
     "ename": "KeyError",
     "evalue": "'w'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[8], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mtransfer\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mw\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mz\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m10\u001b[39;49m\u001b[43m)\u001b[49m\n",
      "Cell \u001b[0;32mIn[3], line 9\u001b[0m, in \u001b[0;36mtransfer\u001b[0;34m(src, dst, amount)\u001b[0m\n\u001b[1;32m      7\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m lock:\n\u001b[1;32m      8\u001b[0m     success \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mFalse\u001b[39;00m\n\u001b[0;32m----> 9\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m \u001b[43mbank_accounts\u001b[49m\u001b[43m[\u001b[49m\u001b[43msrc\u001b[49m\u001b[43m]\u001b[49m \u001b[38;5;241m>\u001b[39m\u001b[38;5;241m=\u001b[39m amount:\n\u001b[1;32m     10\u001b[0m         bank_accounts[src] \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m=\u001b[39m amount\n\u001b[1;32m     11\u001b[0m         bank_accounts[dst] \u001b[38;5;241m+\u001b[39m\u001b[38;5;241m=\u001b[39m amount\n",
      "\u001b[0;31mKeyError\u001b[0m: 'w'"
     ]
    }
   ],
   "source": [
    "transfer(\"w\", \"z\", 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "02262baa-6f4f-455e-b913-accfa894cc18",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "transferred\n",
      "locked inside with? True\n",
      "locked after with? False\n"
     ]
    }
   ],
   "source": [
    "transfer(\"z\", \"x\", 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "1b338a2c-1274-41e8-9179-89b797e4ec2f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'x': 8, 'y': 120, 'z': 197}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bank_accounts"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.13-nogil",
   "language": "python",
   "name": "python3.13-nogil"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}