IBM Support

Locking within the Standard iostream class library

Troubleshooting


Problem

My multi-threaded program's call to std::cin.get blocks calls to std::cout << in other threads.

Cause

A testcase can demonstrate the issue:



    $ cat t.C

    #include <iostream>
    #include <unistd.h>
    #include <pthread.h>

    using namespace std;

    void* thread(void* p)
    {
      int i = 0;

      while (1)
     {

        cout << "thread: i = " << i++ << endl ;
        sleep(2);
      }
      return 0;
    }

    int main()
    {
      pthread_t tid;
      char input;

      pthread_create(&tid, NULL, thread, NULL);
     
      while(1)
      {
        cout << "-> ";
        cin >> input;    // causes "cout <<" in thread() to block
        cout << "input = " << c << endl;
        sleep(1);
      }
      return 0;
    }

    $ xlC_r t.C && ./a.out

    thread: i = 0
    -> ^C <-- thread() is blocked as main thread waits for user input

Resolving The Problem

The behavior observed in the above testcase occurs because of the thread-safe design of the I/O stream classes that are part of the standard VisualAge C++ runtime library. On the other hand, the older USL iostream classes (accessed through #include <iostream.h>) provide greater concurrency, but aren't fully thread-safe.

As a result, only one thread can perform an I/O operation at a time with the standard iostream classes; i.e. it does not permit concurrent I/O operations. This behavior is maintained in the VisualAge C++ runtime, since changing the locking strategy could result in random deadlocks.

In recognition of this limitation, XL C/C++ V7 for AIX provides an option for disabling the locking mechanism at a cost to the user of inheriting the responsibility of maintaining thread-safety. Please consult the XL C/C++ V7 for AIX Programming Guide, chapter "Ensuring thread safety", section "Ensuring thread-safety of stream objects" for usage details of this feature.

[{"Product":{"code":"SSJT9L","label":"XL C\/C++"},"Business Unit":{"code":"BU054","label":"Systems w\/TPS"},"Component":"C\/C++ Runtime","Platform":[{"code":"PF002","label":"AIX"}],"Version":"7.0","Edition":"","Line of Business":{"code":"LOB08","label":"Cognitive Systems"}}]

Document Information

More support for:
XL C/C++

Software version:
7.0

Operating system(s):
AIX

Document number:
76849

Modified date:
12 October 2022

UID

swg21173352