33 Concurrency support library [thread] 33.2 Requirements [thread.req] C++N4910:2022 (708) p1660.cpp

# はじめに(Introduction)

N4910  Working Draft, Standard for Programming Language C++

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/n4910.pdf

C++ n4910は、ISO/IEC JTC1 SC22 WG21の作業原案(Working Draft)です。
公式のISO/IEC 14882原本ではありません。
ISO/IEC JTC1 SC22 のWG21を含むいくつかのWGでは、可能な限り作業文書を公開し、幅広い意見を求めています。

ISO/IEC JTC1 SC7からISO/IEC JTC1 SC22リエゾンとして、2000年頃、C/C++の品質向上に貢献しようとした活動をしていたことがあります。その頃は、まだISO/IEC TS 17961の原案が出る前です。Cの精神が優勢で、セキュリティ対策は補助的な位置付けでした。ISO/IEC TS 17961の制定と、C/C++のライブラリ類の見直しと、C++の進化はどんどん進んでいきます。　

進化の具合が、どちらに行こうとしているかは、コンパイルて実行させてみないとわかりません。C/C++の規格案の電子ファイルは、そのままコンパイルできる形式であるとよいと主張してきました。MISRA-C/C++, CERTC/C++でも同様です。MISRA-C/C++は、Example Suiteという形で、コード断片をコンパイルできる形で提供するようになりました。

一連の記事はコード断片をコンパイルできる形にする方法を検討してコンパイル、リンク、実行して、規格案の原文と処理系(g++, Clang++)との違いを確認し、技術内容を検討し、ISO/IEC JTC1 SC22 WG21にフィードバックするために用います。
また、CERT C++, MISRA C++等のコーディング標準のコード断片をコンパイルする際の参考にさせていただこうと考えています。CERT C++, MISRA C++が標準化の動きとの時間的なずれがあれば確認できれば幸いです。また、boostライブラリとの関連、Linux OS, 箱庭プロジェクト、g++(GCC), clang++(LLVM）との関係も調査中です。
何か、抜け漏れ、耳より情報がありましたらおしらせくださると幸いです。

## 背景(back ground)
C/C++でコンパイルエラーが出ると、途方にくれることがしばしばあります。
何回かに１回は、該当するエラーが検索できます。
ただ、条件が違っていて、そこでの修正方法では目的を達成しないこともしばしばです。いろいろな条件のコンパイルエラーとその対応方法について、広く記録することによって、いつか同じエラーに遭遇した時にやくに立つことを目指しています。

この半年の間で、三度、自分のネットでの記録に助けられたことがあります。
また過去に解決できなかった記録を１０種類以上、最近になって解決できたことがあります。それは、主に次の３つの情報に基づいています。

https://stackoverflow.com

http://ja.cppreference.com/

cpprefjp - C++日本語リファレンス

https://cpprefjp.github.io/

コンパイラの実装状況

https://cpprefjp.github.io/implementation-status.html

また
https://researchmap.jp/joub9b3my-1797580/#_1797580
に記載したサイトのお世話になっています。

## 作業方針(sequence)
Clang++では-std=c++03, C++2bの2種類
g++では-std=c++03, c++2bの２種類
でコンパイルし、

１）コンパイルエラーを収集する。
２）コンパイルエラーをなくす方法を検討する。
コンパイルエラーになる例を示すだけが目的のコードは、コンパイルエラーをなくすのではなく、コンパイルエラーの種類を収集するだけにする。
文法を示すのが目的のコード場合に、コンパイルエラーをなくすのに手間がかかる場合は、順次作業します。
３）リンクエラーをなくす方法を検討する。
文法を示すのが目的のコード場合に、リンクエラーをなくすのに手間がかかる場合は、順次作業します。
４）意味のある出力を作る。
コンパイル、リンクが通っても、意味のある出力を示そうとすると、コンパイル・リンクエラーが出て収拾できそうにない場合がある。順次作業します。

１）だけのものから４）まで進んだものと色々ある状態です。一歩でも前に進むご助言をお待ちしています。「検討事項」の欄に現状を記録するようにしています。

### C++N4910:2022 Standard Working Draft on ISO/IEC 14882(0) sample code compile list  

https://qiita.com/kaizen_nagoya/items/fc957ddddd402004bb91

```macOS:bash
$ docker run -v /Users/ogawakiyoshi/n4910:/Users/ogawakiyoshi/n4910 -it kaizenjapan/n4910 /bin/bash
```

### C++N4741, 2018 Standard Working Draft on ISO/IEC 14882 sample code compile list
https://qiita.com/kaizen_nagoya/items/3294c014044550896010

### C++N4606, 2016符号断片編纂一覧(example code compile list)
C++N4606, 2016 Working Draft 2016, ISO/IEC 14882, C++ standard(1) Example code compile list
https://qiita.com/kaizen_nagoya/items/df5d62c35bd6ed1c3d43/

### C++N3242, 2011 sample code compile list on clang++ and g++
https://qiita.com/kaizen_nagoya/items/685b5c1a2c17c1bf1318

## 読書感想文

CコンパイラによるC言語規格の読書感想文として掲載しています。

コンパイル実験が、C++N4910に対する、G++とClang++による感想文だということご理解いただけると幸いです。

読書感想文は人間かAIだけが作るものとは限りません。
本（電子書籍を含む）を入力として、その内容に対する文字列を読書感想文として受け止めましょう。
元の文章をあり方、コンパイルできるように電子化しておくこと、コンパイラが解釈可能な断片の作り方など。

https://qiita.com/tags/読書感想文

## 個人開発

Cコンパイラの試験を一人でもくもくとやっているのは個人開発の一つの姿です。

https://qiita.com/tags/個人開発

 <この項は書きかけです。順次追記します。>

## 編纂器(Compiler)
### clang++ --version
#####  20220826 以前
> Debian clang version 14.0.5-++20220610033153+c12386ae247c-1~exp1~20220610153237.151
Target: x86_64-pc-linux-gnu, Thread model: posix, InstalledDir: /usr/bin

##### 20220827 以降
> Debian clang version 14.0.6-++20220622053050+f28c006a5895-1~exp1~20220622173135.152
Target: x86_64-pc-linux-gnu　Thread model: posix InstalledDir: /usr/bin

### g++- --version
> g++ (GCC) 12.1.0  Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

#  33 Concurrency support library [thread] 33.2 Requirements [thread.req] C++N4910:2022 (707) p1660.cpp

## 算譜(source code)

```c++:p1660.cpp
// C++N4910 Committee Draft, Standard for Programming Language C++
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/n4910.pdf
const char * n4910 = " 33 Concurrency support library [thread] 33.2 Requirements [thread.req] C++N4910:2022 (707) p1660.cpp";
// Debian clang version 14.0.5-++20220610033153+c12386ae247c-
// g++ (GCC) 12.1.0 Copyright (C) 2022 Free Software Foundation, Inc.
// Edited by Dr. OGAWA Kiyoshi. Compile procedure and results record.
// C++N4910:2022 Standard Working Draft on ISO/IEC 14882(0) sample code compile list
// https://qiita.com/kaizen_nagoya/items/fc957ddddd402004bb91

#include "N4910.h"

using namespace std;

// 33.2.1 Template parameter names [thread.req.paramname]
//  Throughout this Clause, the names of template parameters are used to express type requirements. If a template parameter is named Predicate, operator() applied to the template argument shall return a value that is convertible to bool. If a template parameter is named Clock, the corresponding template argument shall be a type C that meets the Cpp17Clock requirements (29.3); the program is ill-formed if is_clock_v<C> is false.
// 33.2.2 Exceptions [thread.req.exception]
//  Some functions described in this Clause are specified to throw exceptions of type system_error (19.5.8). Such exceptions are thrown if any of the function’s error conditions is detected or a call to an operating system or other underlying API results in an error that prevents the library function from meeting its specifications. Failure to allocate storage is reported as described in 16.4.6.13.
// [Example 1 : Consider a function in this Clause that is specified to throw exceptions of type system_error and specifies error conditions that include operation_not_permitted for a thread that does not have the privilege to perform the operation. Assume that, during the execution of this function, an errno of EPERM is reported by a POSIX API call used by the implementation. Since POSIX specifies an errno of EPERM when “the caller does not have the privilege to perform the operation”, the implementation maps EPERM to an error_condition of operation_not_permitted (19.5) and an exception of type system_error is thrown.
//  The error_code reported by such an exception’s code() member function compares equal to one of the conditions specified in the function’s error condition element.
// 33.2.3 Native handles [thread.req.native]
//  Several classes described in this Clause have members native_handle_type and native_handle. The presence of these members and their semantics is implementation-defined.
// [Note 1: These members allow implementations to provide access to implementation details. Their names are specified to facilitate portable compile-time detection. Actual use of these members is inherently non-portable.
// 33.2.4 Timing specifications [thread.req.timing]
//  Several functions described in this Clause take an argument to specify a timeout. These timeouts are specified as either a duration or a time_point type as specified in Clause 29.
//  Implementations necessarily have some delay in returning from a timeout. Any overhead in interrupt response, function return, and scheduling induces a “quality of implementation” delay, expressed as duration Di. Ideally, this delay would be zero. Further, any contention for processor and memory resources induces a “quality of management” delay, expressed as duration Dm. The delay durations may vary from timeout to timeout, but in all cases shorter is better.
// The functions whose names end in _for take an argument that specifies a duration. These functions produce relative timeouts. Implementations should use a steady clock to measure time for these functions.312 Given a duration argument Dt, the real-time duration of the timeout is Dt + Di + Dm.
// The functions whose names end in _until take an argument that specifies a time point. These functions produce absolute timeouts. Implementations should use the clock specified in the time point to measure time for these functions. Given a clock time point argument Ct, the clock time point of the return from timeout should be Ct + Di + Dm when the clock is not adjusted during the timeout. If the clock is adjusted to the time Ca during the timeout, the behavior should be as follows:
// An implementation returns from such a timeout at any point from the time specified above to the time it would return from a steady-clock relative timeout on the difference between Ct and the time point of the call to the _until function.
// Recommended practice: Implementations should decrease the duration of the wait when the clock is adjusted forwards.
// [Note 2: If the clock is not synchronized with a steady clock, e.g., a // CPU time clock, these timeouts can fail to provide useful functionality.
// The resolution of timing provided by an implementation depends on both operating system and hardware. The finest resolution provided by an implementation is called the native resolution. Implementation-provided clocks that are used for these functions meet the Cpp17TrivialClock requirements (29.3).
// A function that takes an argument which specifies a timeout will throw if, during its execution, a clock, time point, or time duration throws an exception. Such exceptions are referred to as timeout-related exceptions.
// [Note 3: Instantiations of clock, time point and duration types supplied by the implementation as specified in 29.7 do not throw exceptions. —end note]
// 33.2.5 Requirements for Cpp17Lockable types [thread.req.lockable]
// 33.2.5.1 In general [thread.req.lockable.general]
// An execution agent is an entity such as a thread that may perform work in parallel with other execution agents.
// [Note 1: Implementations or users can introduce other kinds of agents such as processes or thread-pool tasks.
// The calling agent is determined by context, e.g., the calling thread that contains the call, and so on.
// [Note 2: Some lockable objects are “agent oblivious” in that they work for any execution agent model because they do not determine or store the agent’s ID (e.g., an ordinary spin lock).
// The standard library templates unique_lock (33.6.5.4), shared_lock (33.6.5.5), scoped_lock (33.6.5.3), lock_guard (33.6.5.2), lock, try_lock (33.6.6), and condition_variable_any (33.7.5) all operate on user- supplied lockable objects. The Cpp17BasicLockable requirements, the Cpp17Lockable requirements, the Cpp17TimedLockable requirements, the Cpp17SharedLockable requirements, and the Cpp17SharedTimedLock- able requirements list the requirements imposed by these library types in order to acquire or release ownership of a lock by a given execution agent.
// 312) Implementations for which standard time units are meaningful will typically have a steady clock within their hardware implementation.
// — If Ca > Ct, the waiting function should wake as soon as possible, i.e., Ca + Di + Dm, since the timeout is already satisfied. This specification may result in the total duration of the wait decreasing when measured against a steady clock.
// — If Ca ≤ Ct, the waiting function should not time out until Clock::now() returns a time Cn ≥ Ct, i.e., waking at Ct + Di + Dm.
// [Note 1: When the clock is adjusted backwards, this specification can result in the total duration of the wait increasing when measured against a steady clock. When the clock is adjusted forwards, this specification can result in the total duration of the wait decreasing when measured against a steady clock.
// Effects: Blocks until a lock can be acquired for the current execution agent. If an exception is thrown then a lock shall not have been acquired for the current execution agent.
// [Note 3: The nature of any lock ownership and any synchronization it entails are not part of these requirements.
//  A lock on an object m is said to be
// — a non-shared lock if it is acquired by a call to lock, try_lock, try_lock_for, or try_lock_until on m, or
// — a shared lock if it is acquired by a call to lock_shared, try_lock_shared, try_lock_shared_for, or try_lock_shared_until on m.
// 33.2.5.2 Cpp17BasicLockable requirements [thread.req.lockable.basic]
//  A type L meets the Cpp17BasicLockable requirements if the following expressions are well-formed and have the specified semantics (m denotes a value of type L).
m.lock()
// [Note 4: Only the method of lock acquisition is considered; the nature of any lock ownership is not part of these definitions.
m.unlock()
// Preconditions: The current execution agent holds a non-shared lock on m.
// Effects: Releases a non-shared lock on m held by the current execution agent. Throws: Nothing.
// 33.2.5.3 Cpp17Lockable requirements [thread.req.lockable.req] 1 A type L meets the Cpp17Lockable requirements if it meets the Cpp17BasicLockable requirements and the following expressions are well-formed and have the specified semantics (m denotes a value of type L). m.try_lock()
//  A type L meets the Cpp17TimedLockable requirements if it meets the Cpp17Lockable requirements and the following expressions are well-formed and have the specified semantics (m denotes a value of type L, rel_time denotes a value of an instantiation of duration (29.5), and abs_time denotes a value of an instantiation of time_point (29.6)).
m.try_lock_for(rel_time)
// Effects: Attempts to acquire a lock for the current execution agent within the relative timeout (33.2.4) specified by rel_time. The function will not return within the timeout specified by rel_time unless it has obtained a lock on m for the current execution agent. If an exception is thrown then a lock has not been acquired for the current execution agent.
// Return type: bool.
// Returns: true if the lock was acquired, otherwise false.
// Effects: Attempts to acquire a lock for the current execution agent without blocking. If an exception is thrown then a lock shall not have been acquired for the current execution agent.
// Return type: bool.
// eturns: true if the lock was acquired, otherwise false.
// 33.2.5.4 Cpp17TimedLockable requirements [thread.req.lockable.timed]
m.try_lock_until(abs_time)
// Effects: Attempts to acquire a lock for the current execution agent before the absolute timeout (33.2.4) specified by abs_time. The function will not return before the timeout specified by abs_time unless it has obtained a lock on m for the current execution agent. If an exception is thrown then a lock has not been acquired for the current execution agent.
// Return type: bool.
// Returns: true if the lock was acquired, otherwise false.
// 33.2.5.5 Cpp17SharedLockable requirements [thread.req.lockable.shared]
//  A type L meets the Cpp17SharedLockable requirements if the following expressions are well-formed, have the specified semantics, and the expression m.try_lock_shared() has type bool (m denotes a value of type L): m.lock_shared()
// A type L meets the Cpp17SharedTimedLockable requirements if it meets the Cpp17SharedLockable requirements, and the following expressions are well-formed, have type bool, and have the specified semantics (m denotes a value of type L, rel_time denotes a value of a specialization of chrono::duration, and abs_time denotes a value of a specialization of chrono::time_point).
m.try_lock_shared_for(rel_time)
// Effects: Blocks until a lock can be acquired for the current execution agent. If an exception is thrown then a lock shall not have been acquired for the current execution agent.
m.try_lock_shared()
// Effects: Attempts to acquire a lock for the current execution agent without blocking. If an exception is thrown then a lock shall not have been acquired for the current execution agent.
// Returns: true if the lock was acquired, false otherwise.
m.unlock_shared()
// Preconditions: The current execution agent holds a shared lock on m.
// Effects: Releases a shared lock on m held by the current execution agent. Throws: Nothing.
// 33.2.5.6 Cpp17SharedTimedLockable requirements [thread.req.lockable.shared.timed]
// Effects: Attempts to acquire a lock for the current execution agent within the relative timeout (33.2.4) specified by rel_time. The function will not return within the timeout specified by rel_time unless it has obtained a lock on m for the current execution agent. If an exception is thrown then a lock has not been acquired for the current execution agent.
// Returns: true if the lock was acquired, false otherwise. m.try_lock_shared_until(abs_time)
// Effects: Attempts to acquire a lock for the current execution agent before the absolute timeout (33.2.4) specified by abs_time. The function will not return before the timeout specified by abs_time unless it has obtained a lock on m for the current execution agent. If an exception is thrown then a lock has not been acquired for the current execution agent.
// Returns: true if the lock was acquired, false otherwise.
int main() {
    cout  <<  n4910 << endl;
    return EXIT_SUCCESS;
}
```

## 編纂・実行結果(compile and go)

```ubuntu:bash
$ clang++ p1660.cpp -std=03 -o p1660l -I. -Wall
In file included from p1660.cpp:10:
In file included from ./N4910.h:11:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/atomic:38:
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/c++0x_warning.h:32:2: error: This file requires compiler and library support for the ISO C++ 2011 standard. This support must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
#error This file requires compiler and library support \
 ^
p1660.cpp:52:1: error: unknown type name 'm'
m.lock()
^
p1660.cpp:52:2: error: cannot use dot operator on a type
m.lock()
 ^
3 errors generated.
$ clang++ p1660.cpp -std=2b -o p1660l -I. -Wall
p1660.cpp:52:1: error: unknown type name 'm'
m.lock()
^
p1660.cpp:52:2: error: cannot use dot operator on a type
m.lock()
 ^
2 errors generated.

$ g++ p1660.cpp -std=03 -o p1660g -I. -Wall
In file included from /usr/local/include/c++/12.1.0/atomic:38,
                 from N4910.h:11,
                 from p1660.cpp:10:
/usr/local/include/c++/12.1.0/bits/c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
   32 | #error This file requires compiler and library support \
      |  ^~~~~
p1660.cpp:52:1: error: 'm' does not name a type; did you mean 'tm'?
   52 | m.lock()
      | ^
      | tm

$ g++ p1660.cpp -std=2b -o p1660g -I. -Wall
p1660.cpp:52:1: error: 'm' does not name a type; did you mean 'tm'?
   52 | m.lock()
      | ^
      | tm
```

# 検討事項(agenda)
コンパイルエラーを取るか、コンパイルエラーの理由を解説する。

<!-- リンクエラーの解説をする。clang++とg++の比較。意味のある出力。
コンパイルエラーを取るか、コンパイルエラーの理由を解説する。-->

## 応用例1　AUTOSAR C++

AUTOSARでC++のコーディング標準を作っている。　
MISRA-C++コーディング標準の改訂をまたずに、C++14に対応したかったためかもしれない。　

Autosar Guidelines C++14 example code compile list

https://qiita.com/kaizen_nagoya/items/8ccbf6675c3494d57a76

MISRA C++, AUTOSAR C++について

https://qiita.com/kaizen_nagoya/items/3436fbd49865e0da7d35

## 応用例2　MISRA C/C++

MISRA C まとめ #include <misra_c.h>

https://qiita.com/kaizen_nagoya/items/f1a79a7cbd281607c7c9

MISRA C++ 5-0-16

https://qiita.com/kaizen_nagoya/items/7df2d4e05db724752a74

## 応用例3 CERT C/C++

SEI CERT C++ Coding Standard AA. Bibliography 確認中。

https://qiita.com/kaizen_nagoya/items/fe06719aef10f3f985ae

MISRA C/C++, AUTOSAR C++, CERT C/C++とC/C++工業標準をコンパイルする

https://qiita.com/kaizen_nagoya/items/8dff19511e42b2593db1

## 応用例4 箱庭　
 箱庭もくもく会 

https://hakoniwa.connpass.com

第11回 未定

箱庭ではUnityをはじめC++を使っているらしい。　

ここでコンパイルしたコードと同じようなコードを使っているか、
ここで出たコンパイルエラーと同じようなエラーがでたかを
いろいろな版のコンパイラでコンパイルして確認していく。

この項目は、箱庭プロジェクトを市場分析の対象として、原則的には、箱庭プロジェクトの外部から分析し、外部から箱庭の広告宣伝のための戦略会議を仮想した結果、仮想「箱庭もくもく会」を開催してみることを企画するものである。　
一切の内容は、箱庭プロジェクト、Athrill, TOPPERSとは無関係である。　
一(いち)参加データアナリストの、個人的なつぶやきです。

仮想戦略会議「箱庭」

https://qiita.com/kaizen_nagoya/items/73cb132707653176a461

お盆には「箱庭」記事を書きましょう「もくもく会」の題材になる（１）

https://qiita.com/kaizen_nagoya/items/a22bf2b1dab0ad3258d4

お盆には「箱庭」記事を書きましょう「もくもく会」の題材になる（2）

https://qiita.com/kaizen_nagoya/items/e3c0ceb2dcc9cf3f3fac


## 自己参考資料(self reference)

関連する自己参照以外は、こちらの先頭に移転。

C言語（C++)に対する誤解、曲解、無理解、爽快。

https://qiita.com/kaizen_nagoya/items/3f3992c9722c1cee2e3a

#include "N4910.h"

https://qiita.com/kaizen_nagoya/items/163a47cef7d6bb1c33a8

C++N4910資料の改善点

https://qiita.com/kaizen_nagoya/items/fb4ceb5d117a54641af3

dockerにclang

https://qiita.com/kaizen_nagoya/items/8829ffeee397eda50e80

docker gnu(gcc/g++) and llvm(clang/clang++)

https://qiita.com/kaizen_nagoya/items/059874ea39c4de64c0f7

コンパイル用shell script C版(clangとgcc)とC++版(clang++とg++)

https://qiita.com/kaizen_nagoya/items/74220c0577a512c2d7da

C++N4910:2022 tag follower 300人超えました。ありがとうございます。

https://qiita.com/kaizen_nagoya/items/a63fb96d351ac5c16ff7

astyle 使ってみた

https://qiita.com/kaizen_nagoya/items/3c9a87a781d53a1a23f3

 ＜この記事は個人の過去の経験に基づく個人の感想です。現在所属する組織、業務とは関係がありません。＞

# 文書履歴(document history)
ver. 0.01 初稿 　20220921