Home > Articles > Engineering > Semiconductor Technologies

Understanding Hardware Transactional Memory in Intel's Haswell Architecture

Haswell is the first mainstream architecture to include hardware support for transactional memory. David Chisnall describes how it works and what it means for developers.
Like this article? We recommend

It's been quite a few years since the last time a new generation of Intel processors excited me. The past decade has been largely categorized by small improvements in instructions-per-click and power efficiency, and large improvements in obscure algorithms that now have dedicated instructions.

Intel's Haswell microarchitecture, however, has something fun and of widespread utility. The transactional memory extensions are relevant to a wide range of applications and, as an added bonus, are actually interesting architecturally.

Transactional Memory

I've written previously about transactional memory. From the point of view of the programmer, it's one of the nicest ways of writing concurrent software. You assume that there's no contention on shared data structures, and you modify them. If contentions exist, the routine fails, and none of your changes become globally visible.

There's just one problem with this approach: Transactional memory implemented entirely in software is slow. The easiest way of implementing software transactional memory (STM) is to acquire a global lock when you enter a transactional region, releasing it when you leave. The problem with this technique is that it completely eliminates all parallelism.

You can use a set of locks for different regions of memory, but this design ends up being very costly for entering transactions. Alternatively, you can use a read-copy-update approach, where you copy all of a data structure, modify it, and then use an atomic compare-and-exchange instruction to make your copy the global one. This approach works well for small data structures, but is very difficult to retrofit to existing programs.

Hardware Transactions

Before we look at how hardware transactional memory (HTM) works, it's worth noting that hardware transactions and optimistic concurrency are nothing new in modern processors. Every processor with a branch predictor does speculative execution of instructions after a branch, either committing the results or aborting and discarding the changes based on whether the branch is really taken.

Transactional memory can be seen as a simple extension of this design, with the state of the cache as well as the state of the registers being part of the processor's internal state, rather than a view on the global state.

Hardware transactional memory also isn't a new idea. IBM's Blue Gene/Q has supported it for a little while, and Sun's Rock CPU was intended to do so (before Oracle canceled it), not to mention a large number of research CPUs over the years. For HTM to be useful, however, you need multiple cores and large caches, a combination that has only occurred relatively recently.

With large caches, a CPU can buffer a large number of memory writes without having to store things out to main memory. A multicore CPU already has a mechanism for cache coherency. This ensures that cache lines representing the same memory address in different cores are synchronized, by maintaining a small state machine for each cache line and requiring it to be in the exclusive state (that is, not present in any other caches) before it can be written. It's fairly easy—conceptually, at least—to extend this approach, simply keeping track of whether a core has tried to modify a memory address that another has in its cache.

The idea behind hardware transactional memory is to allow two cores to execute code speculatively if they touch global state, and both should always succeed unless they touch the same bit of global state. For example, if two cores are updating entries in a tree, both will read from the root to a leaf and then each will modify one leaf. In a traditional locking model, you might have a single lock for the entire tree, so that accesses are serialized. With a transactional approach, each starts a transaction, walks to the desired node, and then updates it. The transactions would always succeed, unless both cores tried to update the same node.

In this case, the hardware keeps track of which cache lines have been read from and which have been written to. If another core reads the same cache line addresses as you do, there's no conflict. If either writes to a cache line that another has read or written to, then there's a conflict, and one of the transactions will fail. (Which one fails is defined by implementation.)

Transactional Failure

There are lots of possible things to do when a transaction fails. The most obvious is simply to restart it. This is very easy to do in hardware: You discard all modified cache lines, reset the registers to their initial state (including the program counter), and continue. Unfortunately, this is one of the cases of a solution that's simple, obvious—and wrong.

The problem with this approach is that it doesn't guarantee forward progress, unless you ensure that at least one transaction will succeed. It also makes it impossible, for example, to respect thread priorities, so a high-priority thread could be starving while a lower-priority thread with shorter transactions always succeeds.

The solution in Blue Gene/Q is also simple: If a transaction fails more than a few times in a row, you acquire a global (per CPU) lock, which prevents any other cores from making forward progress until the starved process is finished. This is a good solution for high-performance computing, where most threads have the same priority and throughput is very important. It's not quite as good for general-purpose computing.

Intel adopts the same approach as Rock: If a transaction fails, you jump to a designated failure handler. In Intel's more traditional HTM model, transactions are bracketed by XBEGIN and XEND instructions. The XBEGIN instruction takes an address as an argument and will jump there if the transaction fails, or continue if it succeeds. The address is provided at the start, so the transaction can abort as soon as a conflict is detected. Intel calls this interface Reduced Transactional Memory (RTM), because it doesn't guarantee that a transaction will ever succeed, even if it doesn't conflict. It may fail for a number of reasons, such as executing some floating-point instructions that aren't supported in transactional mode, running out of cache, poor cache aliasing, receiving an interrupt, and so on. In fact, a conforming implementation of RTM could simply discard all memory writes in a transaction and always fail at XEND.

This design is intended to allow hybrid transactional memory implementations, where HTM is used for the fast path and a much slower software implementation is used for cases that the hardware can't handle. The software path might use a single global lock, or a set of locks for different addresses, or any of the other approaches for STM, but it doesn't need to be very efficient because it shouldn't be used very often.

Hardware Lock Elision

In addition to the RTM interface, Intel provides hardware lock elision (HLE) as a simple way of deploying transactional memory in existing code. The idea of HLE is that mutex lock and unlock operations already implicitly define transactional boundaries. You typically use a mutex to protect a shared data structure. It's a logical extension of existing speculative execution mechanisms for a CPU to execute all of the operations that are inside the mutex operation, failing only if they actually conflict.

In theory, this technique wouldn't be at all useful: You'd only bother protecting a data structure with a mutex if concurrent writes to it would be conflicting. In practice, however, there's always a tradeoff to be made with respect to granularity. Acquiring a lock requires (at least) an atomic operation, which traditionally is quite expensive. If you have coarse-grained locking, the cost of acquiring the locks is relatively small, but the potential for parallelism is also small. In contrast, fine-grained locking is expensive, but allows much more parallelism.

The first attempts to implement parallelism in UNIX kernels protected the entire kernel with a single lock. Any code that entered the kernel acquired the lock. This worked very well when a typical system had one or two CPUs, because it was relatively rare to have two cores calling into the kernel at the same time. On core systems with four to eight CPUs, it became a much bigger problem.

With HLE, the atomic operations that acquire and release the lock are prefixed with XACQUIRE and XRELEASE, respectively. The instruction set in x86 uses a variable-length encoding, where instructions are sometimes prefixed by modifiers. For example, an atomic add is a normal add instruction with the LOCK prefix. The two new prefixes have the same byte encoding as existing prefixes on string-manipulation instructions, which makes no sense on the kinds of operations that are used for locks and therefore are ignored by existing processors. This means that you can deploy them unconditionally and they'll simply be ignored on processors that don't support HLE.

When you acquire a lock with an XACQUIRE-prefixed instruction, the lock isn't actually acquired. The write operation is ignored, but the address is added to the set of addresses that the transaction reads, so the transaction will fail if something else writes to that address (for example, some legacy code trying to acquire the lock with the old instruction). Execution continues until the XRELEASE-prefixed instruction, and the transaction is then committed. If it succeeds, the code acts exactly as it would have if the mutex had been acquired: None of the memory operations conflicted, and the lock has been elided.

If the transaction fails, the thread returns to the start. This time, it actually acquires the lock. The acquire instruction proceeds as if the XACQUIRE prefix didn't exist, and execution proceeds just as it would on any other processor.

This is safer than in the pure transactional memory case, because code using locks should already be written to avoid priority inversion. If it isn't, then it's buggy already; HLE hasn't introduced more bugs.

The nice thing about HLE is that you don't have to think too much about locking granularity (at least, if Haswell is your only deployment target). You can just use very coarse-grained locking, and you'll end up with code that will exhibit as much parallelism as is present in the access patterns, not in the locking designs.

There are some limitations, as with RTM. In both cases, the cache detects concurrent accesses at a cache-line granularity. If you have a large array, for example, and two threads are writing to adjacent elements, this will often cause the transaction to fail spuriously, because the transactional hardware can't distinguish between two accesses to the same address, and two accesses to different addresses in the same cache line.


One of the most complex issues when implementing transactional memory is how to handle nested transactions. If a transaction within another succeeds, it can't be committed immediately in case the outer transaction fails.

With RTM, the hardware simply maintains a counter of the nesting depth and commits the transaction only when the counter reaches zero. This technique simplifies the implementation somewhat, as the hardware has to store only one fallback address: If any transaction within a nested region fails, it can just jump back to the fallback address for the start of the nested set.

Nesting has a subtly different meaning in HLE, where regions are defined by lock acquisitions. A thread that tries to acquire multiple locks can be seen as entering a nested transaction, but the hardware determines how many locks it will try to elide. The first lock will always be elided by a chip that supports HLE, but subsequent ones may not. This makes sense, as locks are usually acquired in a coarse-to-fine order, so the gains from eliding the outer ones are more significant.

Power Considerations

While this design is great for high-end applications on multiple-core machines, it comes at a price. The more work that's executed speculatively, the more time the CPU spends doing work that ultimately will be discarded. Therefore it's unlikely to be a benefit on systems where power is at a premium, such as mobile devices. On these systems, it's better to identify contention earlier and allow one core to sleep or run a different process cheaply while a lock is held. This is one of the ideas behind simultaneous multithreading (hyperthreading, in Intel terminology): Making it cheap to perform context switches, so threads that are blocking can be temporarily descheduled without operating system involvement.

It's not clear exactly where the correct tradeoff is, in terms of power efficiency and multicore scalability. On the same process technology, two 500 MHz cores awill use less power than a single 1 GHz core, so there's a clear power win from making more scalable code. This is especially true in the context of something like ARM's big.LITTLE designs, where running code on two or more Cortex-A7 cores can use less power than running on one Cortex-A15, as long as the extra communication overhead doesn't cost too much.

Intel's transactional memory extensions are another step toward finding the "sweet spot." I wouldn't be at all surprised to find that it's very different between low-power and high-performance systems.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020